学习Android的第二十天

目录

[Android Toast 吐司](#Android Toast 吐司)

常量

常用方法

例子

[Android Notification 状态栏通知](#Android Notification 状态栏通知)

[Notification 的基本布局](#Notification 的基本布局)

扩展布局

Notification ( 状态栏通知 )

相关的方法

例子:

参考文档

[Android AlertDialog 弹出框](#Android AlertDialog 弹出框)

[Android Dialog 继承图谱](#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): 设置要显示的视图。

例子

java 复制代码
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();
    }
}

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 对象:

java 复制代码
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

2、创建 Notification.Builder 对象:

java 复制代码
Notification.Builder builder = new Notification.Builder(context);

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

java 复制代码
builder.setContentTitle("标题")
       .setContentText("内容")
       .setSmallIcon(R.drawable.icon)
       .setAutoCancel(true);  // 点击通知后自动取消通知

4、构建 Notification 对象:

java 复制代码
Notification notification = builder.build();

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

java 复制代码
int notificationId = 1;  // 通知 ID
notificationManager.notify(notificationId, notification);

6、取消通知:如果需要取消通知,可以调用 NotificationManager 对象的 cancel() 方法,并传入对应的通知 ID。

java 复制代码
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 类型的数组作为参数,数组中的元素依次表示振动的延迟时间和振动持续时间。数组中的第一个元素表示振动开始之前的延迟时间,后续的元素交替表示振动持续时间和停止时间。

比如:

java 复制代码
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。这样才能确保通知到达时三色灯会亮起提醒用户。

比如:

java 复制代码
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

XML 复制代码
<?xml version="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

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

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

XML 复制代码
<?xml version="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

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页面。点击"清除通知"按钮则会移除已显示的通知。

参考文档

  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类及其一些重要的子类和相关类:

XML 复制代码
android.content.DialogInterface
└── android.app.Dialog
    └── android.app.AlertDialog
        ├── android.app.DatePickerDialog
        ├── android.app.TimePickerDialog
        └── android.app.ProgressDialog (APl26+,已废弃)

AlertDialog

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

几种常用的对话框

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

普通对话框例子

XML 复制代码
<?xml version="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>
java 复制代码
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();
            }
        });
    }
}

普通列表对话框例子

XML 复制代码
<?xml version="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>
java 复制代码
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();
            }
        });
    }
}

单选列表对话框例子

XML 复制代码
<?xml version="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>
java 复制代码
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();
            }
        });
    }
}

多选列表对话框例子

XML 复制代码
<?xml version="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>
java 复制代码
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();
            }
        });
    }
}

参考文档

  1. Android AlertDialog

  2. Android 对话框

相关推荐
yangyanping201086 小时前
Go语言学习之对象关系映射GORM
jvm·学习·golang
网络工程小王6 小时前
【Transformer架构详解】(学习笔记)
笔记·学习
倒酒小生8 小时前
今日算法学习小结
学习
醇氧8 小时前
【学习】【说人话版】子网划分
学习
不灭锦鲤9 小时前
网络安全学习(面试)
学习·安全·web安全
世人万千丶10 小时前
Flutter 框架跨平台鸿蒙开发 - 鸿蒙版本五子棋游戏应用
学习·flutter·游戏·华为·harmonyos·鸿蒙
Aktx20FNz10 小时前
一文学习 Spring AOP 源码全过程
java·学习·spring
Jay Kay10 小时前
生成式推荐模型学习记录part1
学习
冬奇Lab11 小时前
相机拍照流程:从快门按下到JPEG存储的完整旅程
android·音视频开发·源码阅读
alexhilton11 小时前
在Compose中用Shader实现透明的粘稠元球效果
android·kotlin·android jetpack