目录
Android 中的 Toast 是一种轻量级的消息提示框,用于在屏幕上显示简短的通知消息,通常用于向用户提供一些临时性的信息反馈。Toast 不包含任何按钮,也不需要用户交互,它会在屏幕上显示一段时间后自动消失。而且Toast 是为数不多的没有 XML 创建代码的 UI 控件。
在 Android 中,Toast 类定义了两个常量 LENGTH_LONG 和 LENGTH_SHORT,用于表示 Toast 消息显示的持续时间。这两个常量分别表示显示较长时间和显示较短时间。
可以根据自己的需要选择适当的持续时间来显示 Toast 消息。除了使用这两个常量外,你也可以使用 Toast.setDuration(int duration) 方法来自定义持续时间,传入的参数是以毫秒为单位的时间值。
- package com.example.myapplication;
-
- import android.content.Context;
- import android.os.Bundle;
- import android.view.Gravity;
- import android.widget.TextView;
- import android.widget.Toast;
-
- import androidx.appcompat.app.AppCompatActivity;
-
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- // 创建并显示一个简单的 Toast 消息
- showToast("这是一个简单的 Toast 消息");
-
- // 创建并显示一个自定义位置和持续时间的 Toast 消息
- showToastCustom("这是一个自定义位置和持续时间的 Toast 消息", Gravity.TOP | Gravity.CENTER_HORIZONTAL, Toast.LENGTH_LONG);
-
- // 创建并显示一个包含自定义视图的 Toast 消息
- showCustomViewToast();
- }
-
- // 创建并显示一个简单的 Toast 消息
- private void showToast(String message) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
- }
-
- // 创建并显示一个自定义位置和持续时间的 Toast 消息
- private void showToastCustom(String message, int gravity, int duration) {
- Toast toast = Toast.makeText(this, message, duration);
- toast.setGravity(gravity, 0, 0);
- toast.show();
- }
-
- // 创建并显示一个包含自定义视图的 Toast 消息
- private void showCustomViewToast() {
- Toast toast = new Toast(this);
- toast.setDuration(Toast.LENGTH_SHORT);
-
- // 创建一个 TextView 作为 Toast 的视图
- TextView textView = new TextView(this);
- textView.setText("自定义视图的 Toast 消息");
- textView.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
- textView.setTextColor(getResources().getColor(android.R.color.white));
- textView.setPadding(20, 20, 20, 20);
-
- toast.setView(textView);
- toast.show();
- }
- }
通知栏通知(Notification)在现代智能手机中非常常见,用户经常会从屏幕顶部往下滑,查看通知的内容。通知栏通知是一种用于向用户显示重要信息或提醒的方式,通常用于显示来自应用程序的消息、提醒、更新等。
通过通知栏通知,用户可以方便地了解到新的消息、事件或提醒,而不必打开应用程序。通知通常包括标题、内容、图标以及可能的操作按钮,用户可以通过点击通知来执行相应的操作,比如打开应用程序、查看详细信息等。
通知栏通知在移动应用程序中的应用非常广泛,例如社交应用程序、邮件应用程序、新闻应用程序等,都会使用通知来及时通知用户相关信息。它是一种非常重要的用户交互方式,能够提高用户体验,并使用户更容易地与应用程序进行互动。
通知(Notification)的基本布局通常包括以下组成元素:
在 Android 中,通知可以使用扩展布局来显示更多内容,包括消息的前几行或者图片的预览,从而让用户能够在通知栏中更方便地浏览更多信息。
Android 提供了两种常见的扩展布局供开发者使用:
文本扩展布局:文本扩展布局允许在通知中显示更多的文字内容。通过文本扩展布局,你可以展示更多的消息内容,让用户在通知栏中浏览到整个消息的内容或者更多的相关信息。
图像扩展布局:图像扩展布局允许在通知中显示图片的预览。通过图像扩展布局,你可以在通知中显示图片的缩略图或者预览图,让用户能够在通知栏中快速浏览到图片内容。
在 Android 中,状态栏通知主要涉及到两个类:Notification 和 NotificationManager。
以下是这两个类的主要作用:
Notification 类:
NotificationManager 类:
使用的基本流程
1、获取 NotificationManager 对象:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2、创建 Notification.Builder 对象:
Notification.Builder builder = new Notification.Builder(context);
3、设置通知的属性:通过 Notification.Builder 对象设置通知的各种属性,如标题、内容、图标、声音、震动、点击行为等。例如:
- builder.setContentTitle("标题")
- .setContentText("内容")
- .setSmallIcon(R.drawable.icon)
- .setAutoCancel(true); // 点击通知后自动取消通知
4、构建 Notification 对象:
Notification notification = builder.build();
5、发送通知:使用 NotificationManager 对象的 notify() 方法发送通知。指定一个唯一的通知 ID,以便后续对该通知进行更新或取消。
- int notificationId = 1; // 通知 ID
- notificationManager.notify(notificationId, notification);
6、取消通知:如果需要取消通知,可以调用 NotificationManager 对象的 cancel() 方法,并传入对应的通知 ID。
notificationManager.cancel(notificationId);
1、setContentTitle(CharSequence): 设置通知标题。
2、setContentText(CharSequence): 设置通知内容。
3、setSubText(CharSequence): 设置通知的额外小行文字(API 16+才可用)。
4、setTicker(CharSequence): 设置通知到达时在顶部显示的文字信息。
5、setWhen(long): 设置通知时间,通常使用当前系统时间。
6、setSmallIcon(int): 设置通知右下角的小图标,同时通知栏的左侧也会显示这个小图标。
7、setLargeIcon(Bitmap): 设置通知左侧的大图标。
8、setAutoCancel(boolean): 设置是否点击通知后自动取消通知(默认不取消)。
9、setDefaults(int): 用于向通知添加默认的提醒效果,包括声音、闪灯和振动。你可以通过组合多个属性来设置通知的默认提醒效果。以下是可用的默认属性:
10、setVibrate(long[]): 用于设置通知的振动方式。
传入一个 long 类型的数组作为参数,数组中的元素依次表示振动的延迟时间和振动持续时间。数组中的第一个元素表示振动开始之前的延迟时间,后续的元素交替表示振动持续时间和停止时间。
比如:
builder.setVibrate(new long[] {0, 300, 500, 700});
这样设置后,当通知到达时,会按照指定的振动方式进行振动,即先延迟 0 毫秒,然后振动 300 毫秒,接着延迟 500 毫秒,最后振动 700 毫秒。
11、setLights(int argb, int onMs, int offMs): 设置通知的三色灯效果。参数依次是:灯光的颜色(以 ARGB 格式表示),亮的持续时间(以毫秒为单位),暗的持续时间(以毫秒为单位)。
需要注意的是,并不是所有的颜色都能够被所有的设备所支持。有些设备可能不带有三色灯,或者只支持特定颜色。另外,一些设备可能会忽略一些颜色分量,只显示红色和绿色,而忽略蓝色分量。
此外,要使三色灯提醒生效,还需要为 Notification 设置 flags 为 Notification.FLAG_SHOW_LIGHTS。这样才能确保通知到达时三色灯会亮起提醒用户。
比如:
builder.setLights(Color.RED, 1000, 1000);
这样设置后,当通知到达时,设备的三色灯会以红色亮起,每次亮起持续 1000 毫秒,然后熄灭 1000 毫秒,以此重复。
12、setSound(Uri): 设置接收到通知时的铃声。你可以使用系统默认的铃声,也可以自定义铃声。
以下是几种常见的设置方式:
13、setOngoing(boolean): 设置通知是否为一个正在进行的通知。当参数为 true 时,表示该通知是一个正在进行的通知,通常用于表示用户正在进行的任务或者需要持续显示在通知栏中的通知,例如音乐播放器的通知、正在进行的文件下载、同步操作或者主动网络连接等。
通常情况下,正在进行的通知会显示在通知栏的顶部,不会被用户手动清除,直到相应的任务完成或者用户主动取消。这样可以确保用户可以随时了解到当前任务的状态,而不会因为误操作或者其他原因而意外关闭通知。
14、setProgress(int, int, boolean): 用于设置通知中的进度条。该方法的参数依次为:进度条的最大数值、当前进度以及进度条是否为不确定的。
当进度条为确定的时候,通常用于表示一个正在进行的任务的进度。你可以调用 setProgress(max, progress, false) 来设置通知的进度条,并在任务进行中不断更新进度值,直到任务完成后移除进度条。
当进度条为不确定的时候,通常用于表示一个持续活动正在进行中,但无法准确获知进度的情况。你可以调用 setProgress(0, 0, true) 来设置通知的进度条为不确定的,在操作结束时调用 setProgress(0, 0, false) 并更新通知以移除进度条。
15、setContentIntent(PendingIntent): 用于设置通知的点击行为,即当用户点击通知时将要执行的操作。通常情况下,会使用 PendingIntent 来启动一个 Activity、Service 或者 Broadcast。PendingIntent 相比于直接使用 Intent,它可以设置执行次数,主要用于远程服务通信、闹铃、通知、启动器、短信等场景。
启动 Activity:使用 PendingIntent.getActivity() 方法来获取 PendingIntent,其中第四个参数表示 PendingIntent 的位标识符,可以使用以下值之一:
16、setPriority(int): 设置通知的优先级。根据通知的重要性和紧急程度,你可以选择不同的优先级来提醒用户。
以下是几种常见的优先级:
1、修改activity_main.xml
- "1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:gravity="center"
- tools:context=".MainActivity">
- <Button
- android:id="@+id/btn_show_notification"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="弹出通知"/>
-
- <Button
- android:id="@+id/btn_clear_notification"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="清除通知"
- android:layout_marginTop="16dp"/>
- LinearLayout>
2、修改MainActivity.java
- package com.example.myapplication;
-
- import android.app.NotificationChannel;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.content.Intent;
- import android.os.Build;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.core.app.NotificationCompat;
-
- public class MainActivity extends AppCompatActivity {
-
- private static final String CHANNEL_ID = "my_channel_id";
- private static final int NOTIFICATION_ID = 1;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- createNotificationChannel();
-
- Button btnShowNotification = findViewById(R.id.btn_show_notification);
- Button btnClearNotification = findViewById(R.id.btn_clear_notification);
-
- btnShowNotification.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- showNotification();
- }
- });
-
- btnClearNotification.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- clearNotification();
- }
- });
- }
-
- private void createNotificationChannel() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- CharSequence name = getString(R.string.channel_name);
- String description = getString(R.string.channel_description);
- int importance = NotificationManager.IMPORTANCE_DEFAULT;
- NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
- channel.setDescription(description);
- NotificationManager notificationManager = getSystemService(NotificationManager.class);
- notificationManager.createNotificationChannel(channel);
- }
- }
-
- private void showNotification() {
- Intent intent = new Intent(this, TargetActivity.class);
- PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
-
- NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
- .setSmallIcon(R.drawable.meimei)
- .setContentTitle("我的通知")
- .setContentText("点击查看详情")
- .setContentIntent(pendingIntent)
- .setAutoCancel(true);
-
- NotificationManager notificationManager = getSystemService(NotificationManager.class);
- notificationManager.notify(NOTIFICATION_ID, builder.build());
- }
-
- private void clearNotification() {
- NotificationManager notificationManager = getSystemService(NotificationManager.class);
- notificationManager.cancel(NOTIFICATION_ID);
- }
- }
3、创建TargetActivity.java
- package com.example.myapplication;
-
- import android.os.Bundle;
- import androidx.appcompat.app.AppCompatActivity;
-
- public class TargetActivity extends AppCompatActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_target);
- }
- }
4、创建activity_target.xml
- "1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/notify_detail"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="这是通知详情页" />
-
- LinearLayout>
5、更新AndroidManifest.xml
- <application
- ...>
-
- <activity android:name=".MainActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.LAUNCHER"/>
- intent-filter>
- activity>
- <activity android:name=".TargetActivity">activity>
-
- application>
现在,当用户点击“弹出通知”按钮时,应用会创建并显示一个通知。用户点击这个通知后,应用会打开TargetActivity页面。点击“清除通知”按钮则会移除已显示的通知。
在Android开发中,AlertDialog是一种弹出框(对话框),用于显示信息、提示用户决策或收集用户输入。它可以包含标题、内容、按钮(如确认、取消)等元素。
在Android中,Dialog是一个基本的类,用于创建各种类型的对话框。Dialog类位于android.app包中。有几个常用的对话框类都是直接或间接地继承自Dialog类。下面是一个简化的继承图谱,展示了Dialog类及其一些重要的子类和相关类:
- android.content.DialogInterface
- └── android.app.Dialog
- └── android.app.AlertDialog
- ├── android.app.DatePickerDialog
- ├── android.app.TimePickerDialog
- └── android.app.ProgressDialog (APl26+,已废弃)
AlertDialog在Android中是一个特殊的UI组件,它的创建和使用方式与大多数其他UI控件有所不同。AlertDialog不能直接通过new关键字实例化,也不能在XML布局文件中定义。相反,我们使用AlertDialog的一个内部类,即AlertDialog.Builder,来构建和配置对话框。这种设计模式称为建造者模式(Builder Pattern),它可以帮助我们以更流畅和灵活的方式构建复杂对象。
- "1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:gravity="center"
- tools:context=".MainActivity">
- <Button
- android:id="@+id/showDialogButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="显示对话框"
- android:layout_centerInParent="true" />
- LinearLayout>
- package com.example.myapplication;
-
- import android.content.DialogInterface;
- import android.os.Bundle;
- import androidx.appcompat.app.AlertDialog;
- import androidx.appcompat.app.AppCompatActivity;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
-
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- Button showDialogButton = findViewById(R.id.showDialogButton);
- showDialogButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
- builder.setTitle("确认操作");
- builder.setMessage("你确定要执行这个操作吗?");
- builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- // 用户点击“确定”按钮的操作
- Toast.makeText(MainActivity.this, "操作已确认!", Toast.LENGTH_SHORT).show();
- }
- });
- builder.setNegativeButton("取消", null); // 点击“取消”按钮不做任何事情
-
- builder.show();
- }
- });
- }
- }
- "1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:gravity="center"
- tools:context=".MainActivity">
- <Button
- android:id="@+id/button_show_list_dialog"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="显示列表对话框"
- android:layout_centerInParent="true"/>
- LinearLayout>
- package com.example.myapplication;
-
- import android.os.Bundle;
- import androidx.appcompat.app.AlertDialog;
- import androidx.appcompat.app.AppCompatActivity;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
-
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- Button buttonShowListDialog = findViewById(R.id.button_show_list_dialog);
- buttonShowListDialog.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 列表项
- final String[] items = {"Kotlin", "Java", "Python", "PHP", "C#", "C", "C++"};
- AlertDialog.Builder listDialog = new AlertDialog.Builder(MainActivity.this);
- listDialog.setTitle("选择你喜欢的开发语言");
- // 设置列表项和点击事件
- listDialog.setItems(items, (dialog, which) -> {
- // which参数表示用户点击的项的索引
- Toast.makeText(MainActivity.this, "你选择了" + items[which], Toast.LENGTH_SHORT).show();
- });
-
- // 显示对话框
- listDialog.show();
- }
- });
- }
- }
- "1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:gravity="center"
- tools:context=".MainActivity">
- <Button
- android:id="@+id/button_show_single_choice_dialog"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="显示单选对话框"
- android:layout_centerInParent="true"/>
-
- LinearLayout>
- package com.example.myapplication;
-
- import android.os.Bundle;
- import androidx.appcompat.app.AlertDialog;
- import androidx.appcompat.app.AppCompatActivity;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
-
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- Button buttonShowSingleChoiceDialog = findViewById(R.id.button_show_single_choice_dialog);
- buttonShowSingleChoiceDialog.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 单选列表项
- final String[] items = {"Kotlin", "Java", "Python", "PHP", "C#", "C", "C++"};
- int checkedItem = 0; // 初始选中项的索引
- AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MainActivity.this);
- singleChoiceDialog.setTitle("选择你喜欢的开发语言");
- // 设置单选列表项和点击事件
- singleChoiceDialog.setSingleChoiceItems(items, checkedItem, (dialog, which) -> {
- // which参数表示用户点击的项的索引
- Toast.makeText(MainActivity.this, "你选择了" + items[which], Toast.LENGTH_SHORT).show();
- //dialog.dismiss(); // 关闭对话框
- });
-
- // 显示对话框
- singleChoiceDialog.show();
- }
- });
- }
- }
- "1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:gravity="center"
- tools:context=".MainActivity">
- <Button
- android:id="@+id/button_show_multi_choice_dialog"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="显示多选对话框"
- android:layout_centerInParent="true"/>
-
- LinearLayout>
- package com.example.myapplication;
-
- import android.os.Bundle;
- import androidx.appcompat.app.AlertDialog;
- import androidx.appcompat.app.AppCompatActivity;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
-
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- Button buttonShowMultiChoiceDialog = findViewById(R.id.button_show_multi_choice_dialog);
- buttonShowMultiChoiceDialog.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 多选列表项
- final String[] items = {"Kotlin", "Java", "Python", "PHP", "C#", "C", "C++"};
- boolean[] checkedItems = {false, false, false, false, false, false, false}; // 初始选中状态
- AlertDialog.Builder multiChoiceDialog = new AlertDialog.Builder(MainActivity.this);
- multiChoiceDialog.setTitle("请选择一个或多个选项");
- // 设置多选列表项和点击事件
- multiChoiceDialog.setMultiChoiceItems(items, checkedItems, (dialog, which, isChecked) -> {
- // which参数表示用户点击的项的索引,isChecked表示是否被选中
- checkedItems[which] = isChecked; // 更新选中状态
- });
- // 设置确定按钮及其点击事件
- multiChoiceDialog.setPositiveButton("确定", (dialog, which) -> {
- StringBuilder result = new StringBuilder("你选择了:");
- for (int i = 0; i < items.length; i++) {
- if (checkedItems[i]) {
- result.append(items[i]).append(" ");
- }
- }
- Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
- });
-
- // 显示对话框
- multiChoiceDialog.show();
- }
- });
- }
- }