• 学习Android的第二十天


    目录

    Android Toast 吐司

    常量

    常用方法

    例子

    Android Notification 状态栏通知

    Notification 的基本布局

    扩展布局

    Notification ( 状态栏通知 )

    相关的方法

    例子:

    参考文档

    Android AlertDialog 弹出框

    Android Dialog 继承图谱

    AlertDialog

    几种常用的对话框

    普通对话框例子

    普通列表对话框例子

    单选列表对话框例子

    多选列表对话框例子

    参考文档


    Android Toast 吐司

    Android 中的 Toast 是一种轻量级的消息提示框,用于在屏幕上显示简短的通知消息,通常用于向用户提供一些临时性的信息反馈。Toast 不包含任何按钮,也不需要用户交互,它会在屏幕上显示一段时间后自动消失。而且Toast 是为数不多的没有 XML 创建代码的 UI 控件。

    常量

    在 Android 中,Toast 类定义了两个常量 LENGTH_LONG 和 LENGTH_SHORT,用于表示 Toast 消息显示的持续时间。这两个常量分别表示显示较长时间和显示较短时间。

    • LENGTH_LONG 表示 Toast 消息将会显示较长时间。
    • LENGTH_SHORT 表示 Toast 消息将会显示较短时间。

    可以根据自己的需要选择适当的持续时间来显示 Toast 消息。除了使用这两个常量外,你也可以使用 Toast.setDuration(int duration) 方法来自定义持续时间,传入的参数是以毫秒为单位的时间值。

    常用方法

    • void cancel(): 如果 Toast 已经显示,则关闭 Toast,如果 Toast 还未显示,则取消显示。
    • void show(): 显示 Toast 消息。
    • int getDuration(): 返回当前 Toast 消息的持续时间。
    • int getGravity(): 获取 Toast 应显示在屏幕上的位置。
    • float getHorizontalMargin(): 返回水平边距。
    • float getVerticalMargin(): 返回垂直边距。
    • View getView(): 返回 Toast 的 View。
    • int getXOffset(): 以像素为单位返回 X 偏移量。
    • int getYOffset(): 以像素为单位返回 Y 偏移量。
    • static Toast makeText(Context context, int resId, int duration): 创建 Toast 用于显示给定的资源。
    • static Toast makeText(Context context, CharSequence text, int duration): 创建 Toast 用于显示给定的文本。
    • void setDuration(int duration): 设置 Toast 的显示时间。
    • void setGravity(int gravity, int xOffset, int yOffset): 设置 Toast 在屏幕上显示的位置。
    • void setMargin(float horizontalMargin, float verticalMargin): 设置视图的边距。
    • void setText(int resId): 用一个资源更新 Toast 要显示的文本或资源。
    • void setText(CharSequence s): 用一段文本更新 Toast 要显示的文本或资源。
    • void setView(View view): 设置要显示的视图。

    例子

    1. package com.example.myapplication;
    2. import android.content.Context;
    3. import android.os.Bundle;
    4. import android.view.Gravity;
    5. import android.widget.TextView;
    6. import android.widget.Toast;
    7. import androidx.appcompat.app.AppCompatActivity;
    8. public class MainActivity extends AppCompatActivity {
    9. @Override
    10. protected void onCreate(Bundle savedInstanceState) {
    11. super.onCreate(savedInstanceState);
    12. setContentView(R.layout.activity_main);
    13. // 创建并显示一个简单的 Toast 消息
    14. showToast("这是一个简单的 Toast 消息");
    15. // 创建并显示一个自定义位置和持续时间的 Toast 消息
    16. showToastCustom("这是一个自定义位置和持续时间的 Toast 消息", Gravity.TOP | Gravity.CENTER_HORIZONTAL, Toast.LENGTH_LONG);
    17. // 创建并显示一个包含自定义视图的 Toast 消息
    18. showCustomViewToast();
    19. }
    20. // 创建并显示一个简单的 Toast 消息
    21. private void showToast(String message) {
    22. Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    23. }
    24. // 创建并显示一个自定义位置和持续时间的 Toast 消息
    25. private void showToastCustom(String message, int gravity, int duration) {
    26. Toast toast = Toast.makeText(this, message, duration);
    27. toast.setGravity(gravity, 0, 0);
    28. toast.show();
    29. }
    30. // 创建并显示一个包含自定义视图的 Toast 消息
    31. private void showCustomViewToast() {
    32. Toast toast = new Toast(this);
    33. toast.setDuration(Toast.LENGTH_SHORT);
    34. // 创建一个 TextView 作为 Toast 的视图
    35. TextView textView = new TextView(this);
    36. textView.setText("自定义视图的 Toast 消息");
    37. textView.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
    38. textView.setTextColor(getResources().getColor(android.R.color.white));
    39. textView.setPadding(20, 20, 20, 20);
    40. toast.setView(textView);
    41. toast.show();
    42. }
    43. }

    Android Notification 状态栏通知

    通知栏通知(Notification)在现代智能手机中非常常见,用户经常会从屏幕顶部往下滑,查看通知的内容。通知栏通知是一种用于向用户显示重要信息或提醒的方式,通常用于显示来自应用程序的消息、提醒、更新等。

    通过通知栏通知,用户可以方便地了解到新的消息、事件或提醒,而不必打开应用程序。通知通常包括标题、内容、图标以及可能的操作按钮,用户可以通过点击通知来执行相应的操作,比如打开应用程序、查看详细信息等。

    通知栏通知在移动应用程序中的应用非常广泛,例如社交应用程序、邮件应用程序、新闻应用程序等,都会使用通知来及时通知用户相关信息。它是一种非常重要的用户交互方式,能够提高用户体验,并使用户更容易地与应用程序进行互动。

    Notification 的基本布局

    通知(Notification)的基本布局通常包括以下组成元素:

    • Icon/Photo(大图标):通知的大图标,用于表示通知的来源或者类型。通常是应用程序的图标或者相关图片。
    • Title/Name(标题):通知的标题,用于简要描述通知的内容或者来源。通常会放置在通知的顶部。
    • Message(内容信息):通知的详细内容或者信息。通常是通知的主要内容,可以是文本、图片、链接等。
    • Timestamp(通知时间):通知的时间戳,即通知被创建或发送的时间。默认情况下,通知的时间是通知被创建的时间,但也可以通过 setWhen() 方法来设置自定义的时间。
    • Secondary Icon(小图标):通知中的一个较小的图标,通常用于补充说明或者表示附加信息。比如,通知来自某个应用程序,小图标可能是该应用程序的标志性图标。
    • 内容文字:在小图标的左侧或者上方的一个文字,用于描述通知的附加信息,例如通知的类别或者状态等。

    扩展布局

    在 Android 中,通知可以使用扩展布局来显示更多内容,包括消息的前几行或者图片的预览,从而让用户能够在通知栏中更方便地浏览更多信息。

    Android 提供了两种常见的扩展布局供开发者使用:

    1. 文本扩展布局:文本扩展布局允许在通知中显示更多的文字内容。通过文本扩展布局,你可以展示更多的消息内容,让用户在通知栏中浏览到整个消息的内容或者更多的相关信息。

    2. 图像扩展布局:图像扩展布局允许在通知中显示图片的预览。通过图像扩展布局,你可以在通知中显示图片的缩略图或者预览图,让用户能够在通知栏中快速浏览到图片内容。

    Notification ( 状态栏通知 )

    在 Android 中,状态栏通知主要涉及到两个类:Notification 和 NotificationManager。

    • Notification(通知信息类):Notification 类用于定义通知的各种属性,包括通知的图标、标题、内容、声音、震动、点击行为等。通过设置 Notification 对象的属性,开发者可以创建具有不同特性和行为的通知。Notification 类中的属性对应着通知栏的各个部分,可以通过构建一个 Notification 对象来创建一条通知。
    • NotificationManager(状态栏通知管理类):NotificationManager 类是用于管理状态栏通知的管理类,负责发出通知、更新通知、清除通知等操作。开发者通过 NotificationManager 对象来发送创建好的通知,并对通知进行管理。通常,每个应用程序都有自己的 NotificationManager 实例,用于管理其自己的通知。

    以下是这两个类的主要作用:

    Notification 类:

    • 用于定义通知的各种属性,如图标、标题、内容等。
    • 可以设置通知的行为,如点击通知时打开某个 Activity 或者执行某个 Intent。
    • 通过创建 Notification 对象,可以构建具体的通知内容。

    NotificationManager 类:

    • 用于发出通知,即将创建好的通知显示在状态栏上。
    • 可以更新已有的通知,例如更改通知的内容、图标等。
    • 可以取消通知,即清除状态栏上的通知。

    使用的基本流程

    1、获取 NotificationManager 对象:

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    

    2、创建 Notification.Builder 对象:

    Notification.Builder builder = new Notification.Builder(context);
    

    3、设置通知的属性:通过 Notification.Builder 对象设置通知的各种属性,如标题、内容、图标、声音、震动、点击行为等。例如:

    1. builder.setContentTitle("标题")
    2. .setContentText("内容")
    3. .setSmallIcon(R.drawable.icon)
    4. .setAutoCancel(true); // 点击通知后自动取消通知

    4、构建 Notification 对象:

    Notification notification = builder.build();
    

    5、发送通知:使用 NotificationManager 对象的 notify() 方法发送通知。指定一个唯一的通知 ID,以便后续对该通知进行更新或取消。

    1. int notificationId = 1; // 通知 ID
    2. 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): 用于向通知添加默认的提醒效果,包括声音、闪灯和振动。你可以通过组合多个属性来设置通知的默认提醒效果。以下是可用的默认属性:

    • Notification.DEFAULT_VIBRATE: 添加默认的振动提醒。
    • Notification.DEFAULT_SOUND: 添加默认的声音提醒。
    • Notification.DEFAULT_LIGHTS: 添加默认的三色灯提醒。
    • Notification.DEFAULT_ALL: 添加默认的以上三种全部提醒效果。

    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 格式表示),亮的持续时间(以毫秒为单位),暗的持续时间(以毫秒为单位)。

    • argb:灯光的颜色,使用 ARGB 格式表示,即一个 32 位的颜色值,其中包括透明度(A)、红色(R)、绿色(G)和蓝色(B)分量。
    • onMs:灯光亮起的持续时间,以毫秒为单位。
    • offMs:灯光暗下去的持续时间,以毫秒为单位。

    需要注意的是,并不是所有的颜色都能够被所有的设备所支持。有些设备可能不带有三色灯,或者只支持特定颜色。另外,一些设备可能会忽略一些颜色分量,只显示红色和绿色,而忽略蓝色分量。

    此外,要使三色灯提醒生效,还需要为 Notification 设置 flags 为 Notification.FLAG_SHOW_LIGHTS。这样才能确保通知到达时三色灯会亮起提醒用户。

    比如:

    builder.setLights(Color.RED, 1000, 1000);

    这样设置后,当通知到达时,设备的三色灯会以红色亮起,每次亮起持续 1000 毫秒,然后熄灭 1000 毫秒,以此重复。 

    12、setSound(Uri): 设置接收到通知时的铃声。你可以使用系统默认的铃声,也可以自定义铃声。

    以下是几种常见的设置方式:

    • 获取默认铃声:你可以使用 setDefaults(Notification.DEFAULT_SOUND) 来设置通知的默认铃声。这将使用系统默认的铃声来提醒用户。
    • 获取自定义铃声:如果你有自定义的铃声文件,你可以通过指定铃声文件的 Uri 来设置通知的铃声。例如:builder.setSound(Uri.parse("file:///sdcard/xx/xx.mp3"));
    • 获取 Android 多媒体库内的铃声:也可以从 Android 多媒体库内获取铃声。例如,使用 Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "5") 来获取多媒体库中的第五个铃声。

    13、setOngoing(boolean): 设置通知是否为一个正在进行的通知。当参数为 true 时,表示该通知是一个正在进行的通知,通常用于表示用户正在进行的任务或者需要持续显示在通知栏中的通知,例如音乐播放器的通知、正在进行的文件下载、同步操作或者主动网络连接等。

    通常情况下,正在进行的通知会显示在通知栏的顶部,不会被用户手动清除,直到相应的任务完成或者用户主动取消。这样可以确保用户可以随时了解到当前任务的状态,而不会因为误操作或者其他原因而意外关闭通知。

    14、setProgress(int, int, boolean): 用于设置通知中的进度条。该方法的参数依次为:进度条的最大数值、当前进度以及进度条是否为不确定的。

    • max:进度条的最大数值。
    • progress:当前的进度值。
    • indeterminate:进度条是否为不确定的。如果为 true,则表示进度条为不确定的;如果为 false,则表示进度条为确定的。

    当进度条为确定的时候,通常用于表示一个正在进行的任务的进度。你可以调用 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 的位标识符,可以使用以下值之一:

    • FLAG_ONE_SHOT: 表示返回的 PendingIntent 仅能执行一次,执行完后自动取消。
    • FLAG_NO_CREATE: 表示如果描述的 PendingIntent 不存在,则不创建相应的 PendingIntent,而是返回 null。
    • FLAG_CANCEL_CURRENT: 表示相应的 PendingIntent 已经存在,则取消前者,然后创建新的 PendingIntent。
    • FLAG_UPDATE_CURRENT: 表示更新 PendingIntent。

    16、setPriority(int): 设置通知的优先级。根据通知的重要性和紧急程度,你可以选择不同的优先级来提醒用户。

    以下是几种常见的优先级:

    • Notification.PRIORITY_MAX:用于表示重要且紧急的通知,通知用户这个事件是时间上紧迫的或者需要立即处理的。
    • Notification.PRIORITY_HIGH:用于重要的通信内容,例如短消息或者聊天,这些都是对用户来说比较有兴趣的。
    • Notification.PRIORITY_DEFAULT:默认优先级,用于没有特殊优先级分类的通知。
    • Notification.PRIORITY_LOW:用于通知用户但不是很紧急的事件。
    • Notification.PRIORITY_MIN:用于后台消息,例如天气或者位置信息。最低优先级通知将只在状态栏显示图标,只有用户下拉通知抽屉才能看到内容。

    例子:

    1、修改activity_main.xml

    1. "1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. xmlns:tools="http://schemas.android.com/tools"
    6. android:orientation="vertical"
    7. android:gravity="center"
    8. tools:context=".MainActivity">
    9. <Button
    10. android:id="@+id/btn_show_notification"
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:text="弹出通知"/>
    14. <Button
    15. android:id="@+id/btn_clear_notification"
    16. android:layout_width="wrap_content"
    17. android:layout_height="wrap_content"
    18. android:text="清除通知"
    19. android:layout_marginTop="16dp"/>
    20. LinearLayout>

    2、修改MainActivity.java

    1. package com.example.myapplication;
    2. import android.app.NotificationChannel;
    3. import android.app.NotificationManager;
    4. import android.app.PendingIntent;
    5. import android.content.Intent;
    6. import android.os.Build;
    7. import android.os.Bundle;
    8. import android.view.View;
    9. import android.widget.Button;
    10. import androidx.appcompat.app.AppCompatActivity;
    11. import androidx.core.app.NotificationCompat;
    12. public class MainActivity extends AppCompatActivity {
    13. private static final String CHANNEL_ID = "my_channel_id";
    14. private static final int NOTIFICATION_ID = 1;
    15. @Override
    16. protected void onCreate(Bundle savedInstanceState) {
    17. super.onCreate(savedInstanceState);
    18. setContentView(R.layout.activity_main);
    19. createNotificationChannel();
    20. Button btnShowNotification = findViewById(R.id.btn_show_notification);
    21. Button btnClearNotification = findViewById(R.id.btn_clear_notification);
    22. btnShowNotification.setOnClickListener(new View.OnClickListener() {
    23. @Override
    24. public void onClick(View v) {
    25. showNotification();
    26. }
    27. });
    28. btnClearNotification.setOnClickListener(new View.OnClickListener() {
    29. @Override
    30. public void onClick(View v) {
    31. clearNotification();
    32. }
    33. });
    34. }
    35. private void createNotificationChannel() {
    36. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    37. CharSequence name = getString(R.string.channel_name);
    38. String description = getString(R.string.channel_description);
    39. int importance = NotificationManager.IMPORTANCE_DEFAULT;
    40. NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
    41. channel.setDescription(description);
    42. NotificationManager notificationManager = getSystemService(NotificationManager.class);
    43. notificationManager.createNotificationChannel(channel);
    44. }
    45. }
    46. private void showNotification() {
    47. Intent intent = new Intent(this, TargetActivity.class);
    48. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
    49. NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
    50. .setSmallIcon(R.drawable.meimei)
    51. .setContentTitle("我的通知")
    52. .setContentText("点击查看详情")
    53. .setContentIntent(pendingIntent)
    54. .setAutoCancel(true);
    55. NotificationManager notificationManager = getSystemService(NotificationManager.class);
    56. notificationManager.notify(NOTIFICATION_ID, builder.build());
    57. }
    58. private void clearNotification() {
    59. NotificationManager notificationManager = getSystemService(NotificationManager.class);
    60. notificationManager.cancel(NOTIFICATION_ID);
    61. }
    62. }

    3、创建TargetActivity.java

    1. package com.example.myapplication;
    2. import android.os.Bundle;
    3. import androidx.appcompat.app.AppCompatActivity;
    4. public class TargetActivity extends AppCompatActivity {
    5. @Override
    6. protected void onCreate(Bundle savedInstanceState) {
    7. super.onCreate(savedInstanceState);
    8. setContentView(R.layout.activity_target);
    9. }
    10. }

    4、创建activity_target.xml

    1. "1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. android:orientation="vertical" >
    6. <TextView
    7. android:id="@+id/notify_detail"
    8. android:layout_width="match_parent"
    9. android:layout_height="wrap_content"
    10. android:text="这是通知详情页" />
    11. LinearLayout>

    5、更新AndroidManifest.xml

    1. <application
    2. ...>
    3. <activity android:name=".MainActivity">
    4. <intent-filter>
    5. <action android:name="android.intent.action.MAIN"/>
    6. <category android:name="android.intent.category.LAUNCHER"/>
    7. intent-filter>
    8. activity>
    9. <activity android:name=".TargetActivity">activity>
    10. application>

    现在,当用户点击“弹出通知”按钮时,应用会创建并显示一个通知。用户点击这个通知后,应用会打开TargetActivity页面。点击“清除通知”按钮则会移除已显示的通知。

    参考文档

    1. 设计思想 : Notifications in Android 4.4 and Lower

    2. API文档 : Notification

    3. Notification.Builder 官方 API 文档

    Android AlertDialog 弹出框

    Android开发中,AlertDialog是一种弹出框(对话框),用于显示信息、提示用户决策或收集用户输入。它可以包含标题、内容、按钮(如确认、取消)等元素。

    Android Dialog 继承图谱

    在Android中,Dialog是一个基本的类,用于创建各种类型的对话框。Dialog类位于android.app包中。有几个常用的对话框类都是直接或间接地继承自Dialog类。下面是一个简化的继承图谱,展示了Dialog类及其一些重要的子类和相关类:

    1. android.content.DialogInterface
    2. └── android.app.Dialog
    3. └── android.app.AlertDialog
    4. ├── android.app.DatePickerDialog
    5. ├── android.app.TimePickerDialog
    6. └── android.app.ProgressDialog (APl26+,已废弃)

    AlertDialog

    AlertDialog在Android中是一个特殊的UI组件,它的创建和使用方式与大多数其他UI控件有所不同。AlertDialog不能直接通过new关键字实例化,也不能在XML布局文件中定义。相反,我们使用AlertDialog的一个内部类,即AlertDialog.Builder,来构建和配置对话框。这种设计模式称为建造者模式(Builder Pattern),它可以帮助我们以更流畅和灵活的方式构建复杂对象。

    几种常用的对话框

    1. 普通对话框
    2. 普通列表对话框
    3. 单选列表对话框
    4. 多选列表对话框

    普通对话框例子

    1. "1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. xmlns:tools="http://schemas.android.com/tools"
    6. android:orientation="vertical"
    7. android:gravity="center"
    8. tools:context=".MainActivity">
    9. <Button
    10. android:id="@+id/showDialogButton"
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:text="显示对话框"
    14. android:layout_centerInParent="true" />
    15. LinearLayout>
    1. package com.example.myapplication;
    2. import android.content.DialogInterface;
    3. import android.os.Bundle;
    4. import androidx.appcompat.app.AlertDialog;
    5. import androidx.appcompat.app.AppCompatActivity;
    6. import android.view.View;
    7. import android.widget.Button;
    8. import android.widget.Toast;
    9. public class MainActivity extends AppCompatActivity {
    10. @Override
    11. protected void onCreate(Bundle savedInstanceState) {
    12. super.onCreate(savedInstanceState);
    13. setContentView(R.layout.activity_main);
    14. Button showDialogButton = findViewById(R.id.showDialogButton);
    15. showDialogButton.setOnClickListener(new View.OnClickListener() {
    16. @Override
    17. public void onClick(View v) {
    18. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    19. builder.setTitle("确认操作");
    20. builder.setMessage("你确定要执行这个操作吗?");
    21. builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    22. @Override
    23. public void onClick(DialogInterface dialog, int which) {
    24. // 用户点击“确定”按钮的操作
    25. Toast.makeText(MainActivity.this, "操作已确认!", Toast.LENGTH_SHORT).show();
    26. }
    27. });
    28. builder.setNegativeButton("取消", null); // 点击“取消”按钮不做任何事情
    29. builder.show();
    30. }
    31. });
    32. }
    33. }

    普通列表对话框例子

    1. "1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. xmlns:tools="http://schemas.android.com/tools"
    6. android:orientation="vertical"
    7. android:gravity="center"
    8. tools:context=".MainActivity">
    9. <Button
    10. android:id="@+id/button_show_list_dialog"
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:text="显示列表对话框"
    14. android:layout_centerInParent="true"/>
    15. LinearLayout>
    1. package com.example.myapplication;
    2. import android.os.Bundle;
    3. import androidx.appcompat.app.AlertDialog;
    4. import androidx.appcompat.app.AppCompatActivity;
    5. import android.view.View;
    6. import android.widget.Button;
    7. import android.widget.Toast;
    8. public class MainActivity extends AppCompatActivity {
    9. @Override
    10. protected void onCreate(Bundle savedInstanceState) {
    11. super.onCreate(savedInstanceState);
    12. setContentView(R.layout.activity_main);
    13. Button buttonShowListDialog = findViewById(R.id.button_show_list_dialog);
    14. buttonShowListDialog.setOnClickListener(new View.OnClickListener() {
    15. @Override
    16. public void onClick(View v) {
    17. // 列表项
    18. final String[] items = {"Kotlin", "Java", "Python", "PHP", "C#", "C", "C++"};
    19. AlertDialog.Builder listDialog = new AlertDialog.Builder(MainActivity.this);
    20. listDialog.setTitle("选择你喜欢的开发语言");
    21. // 设置列表项和点击事件
    22. listDialog.setItems(items, (dialog, which) -> {
    23. // which参数表示用户点击的项的索引
    24. Toast.makeText(MainActivity.this, "你选择了" + items[which], Toast.LENGTH_SHORT).show();
    25. });
    26. // 显示对话框
    27. listDialog.show();
    28. }
    29. });
    30. }
    31. }

    单选列表对话框例子

    1. "1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. xmlns:tools="http://schemas.android.com/tools"
    6. android:orientation="vertical"
    7. android:gravity="center"
    8. tools:context=".MainActivity">
    9. <Button
    10. android:id="@+id/button_show_single_choice_dialog"
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:text="显示单选对话框"
    14. android:layout_centerInParent="true"/>
    15. LinearLayout>
    1. package com.example.myapplication;
    2. import android.os.Bundle;
    3. import androidx.appcompat.app.AlertDialog;
    4. import androidx.appcompat.app.AppCompatActivity;
    5. import android.view.View;
    6. import android.widget.Button;
    7. import android.widget.Toast;
    8. public class MainActivity extends AppCompatActivity {
    9. @Override
    10. protected void onCreate(Bundle savedInstanceState) {
    11. super.onCreate(savedInstanceState);
    12. setContentView(R.layout.activity_main);
    13. Button buttonShowSingleChoiceDialog = findViewById(R.id.button_show_single_choice_dialog);
    14. buttonShowSingleChoiceDialog.setOnClickListener(new View.OnClickListener() {
    15. @Override
    16. public void onClick(View v) {
    17. // 单选列表项
    18. final String[] items = {"Kotlin", "Java", "Python", "PHP", "C#", "C", "C++"};
    19. int checkedItem = 0; // 初始选中项的索引
    20. AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MainActivity.this);
    21. singleChoiceDialog.setTitle("选择你喜欢的开发语言");
    22. // 设置单选列表项和点击事件
    23. singleChoiceDialog.setSingleChoiceItems(items, checkedItem, (dialog, which) -> {
    24. // which参数表示用户点击的项的索引
    25. Toast.makeText(MainActivity.this, "你选择了" + items[which], Toast.LENGTH_SHORT).show();
    26. //dialog.dismiss(); // 关闭对话框
    27. });
    28. // 显示对话框
    29. singleChoiceDialog.show();
    30. }
    31. });
    32. }
    33. }

    多选列表对话框例子

    1. "1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. xmlns:tools="http://schemas.android.com/tools"
    6. android:orientation="vertical"
    7. android:gravity="center"
    8. tools:context=".MainActivity">
    9. <Button
    10. android:id="@+id/button_show_multi_choice_dialog"
    11. android:layout_width="wrap_content"
    12. android:layout_height="wrap_content"
    13. android:text="显示多选对话框"
    14. android:layout_centerInParent="true"/>
    15. LinearLayout>
    1. package com.example.myapplication;
    2. import android.os.Bundle;
    3. import androidx.appcompat.app.AlertDialog;
    4. import androidx.appcompat.app.AppCompatActivity;
    5. import android.view.View;
    6. import android.widget.Button;
    7. import android.widget.Toast;
    8. public class MainActivity extends AppCompatActivity {
    9. @Override
    10. protected void onCreate(Bundle savedInstanceState) {
    11. super.onCreate(savedInstanceState);
    12. setContentView(R.layout.activity_main);
    13. Button buttonShowMultiChoiceDialog = findViewById(R.id.button_show_multi_choice_dialog);
    14. buttonShowMultiChoiceDialog.setOnClickListener(new View.OnClickListener() {
    15. @Override
    16. public void onClick(View v) {
    17. // 多选列表项
    18. final String[] items = {"Kotlin", "Java", "Python", "PHP", "C#", "C", "C++"};
    19. boolean[] checkedItems = {false, false, false, false, false, false, false}; // 初始选中状态
    20. AlertDialog.Builder multiChoiceDialog = new AlertDialog.Builder(MainActivity.this);
    21. multiChoiceDialog.setTitle("请选择一个或多个选项");
    22. // 设置多选列表项和点击事件
    23. multiChoiceDialog.setMultiChoiceItems(items, checkedItems, (dialog, which, isChecked) -> {
    24. // which参数表示用户点击的项的索引,isChecked表示是否被选中
    25. checkedItems[which] = isChecked; // 更新选中状态
    26. });
    27. // 设置确定按钮及其点击事件
    28. multiChoiceDialog.setPositiveButton("确定", (dialog, which) -> {
    29. StringBuilder result = new StringBuilder("你选择了:");
    30. for (int i = 0; i < items.length; i++) {
    31. if (checkedItems[i]) {
    32. result.append(items[i]).append(" ");
    33. }
    34. }
    35. Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
    36. });
    37. // 显示对话框
    38. multiChoiceDialog.show();
    39. }
    40. });
    41. }
    42. }

    参考文档

    1. Android AlertDialog

    2. Android 对话框

  • 相关阅读:
    Linux文件系统
    Latex常用宏包\usepackage
    SpringMVC-针对处理器中的参数提供了许多参数解析器
    网络布局搭配clip-path实现无规则图形
    华为电量分段图表实现过程
    谷粒商城十二性能压测
    SpringBoot项目整合RabbitMQ
    7. Spring Boot2.5 安全机制与 REST API 身份验证实战
    tcp为啥是三次握手和四次挥手
    Boost搜索引擎
  • 原文地址:https://blog.csdn.net/m0_74293254/article/details/136393552