Android -AlertDialog 对话框

准备

IDE:

Android Studio 4.1.1
Build #AI-201.8743.12.41.6953283, built on November 5, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0

Android Virtual Devices:

Name: Pixel_2_API_28
CPU/ABI: Google Play Intel Atom (x86)
Path: C:\Users\86188\.android\avd\Pixel_2_API_28.avd
Target: google_apis_playstore [Google Play] (API level 28)
Skin: pixel_2
SD Card: 512M
fastboot.chosenSnapshotFile: 
runtime.network.speed: full
hw.accelerometer: yes
hw.device.name: pixel_2
hw.lcd.width: 1080
hw.initialOrientation: Portrait
image.androidVersion.api: 28
tag.id: google_apis_playstore
hw.mainKeys: no
hw.camera.front: emulated
avd.ini.displayname: Pixel 2 API 28
hw.gpu.mode: auto
hw.ramSize: 1536
PlayStore.enabled: true
fastboot.forceColdBoot: no
hw.cpu.ncore: 4
hw.keyboard: yes
hw.sensors.proximity: yes
hw.dPad: no
hw.lcd.height: 1920
vm.heapSize: 256
skin.dynamic: yes
hw.device.manufacturer: Google
hw.gps: yes
hw.audioInput: yes
image.sysdir.1: system-images\android-28\google_apis_playstore\x86\
showDeviceFrame: yes
hw.camera.back: virtualscene
AvdId: Pixel_2_API_28
hw.lcd.density: 420
hw.arc: false
hw.device.hash2: MD5:55acbc835978f326788ed66a5cd4c9a7
fastboot.forceChosenSnapshotBoot: no
fastboot.forceFastBoot: yes
hw.trackBall: no
hw.battery: yes
hw.sdCard: yes
tag.display: Google Play
runtime.network.latency: none
disk.dataPartition.size: 6442450944
hw.sensors.orientation: yes
avd.ini.encoding: UTF-8
hw.gpu.enabled: yes

注意:以下示例仅在安卓虚拟设备上运行测试,并没有在真实的设备上运行测试。

项目

简单的对话框

  1. 新建项目,选择 Empty Activity,在配置项目时,我选择的 Minimum SDKAPI 16: Android 4.1 (Jelly Bean)

  2. 编辑 src\main\res\layout\activity_main.xml 文件,删除原有的 TextView 元素,新增 Button 元素:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:text="Open Alert Dialog"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  3. 编辑 MainActivity 文件,关于 AlertDialog 的代码在第 34 ~ 58 行:

    package com.mk;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
          
          
    
        private Context context;
        private Button button = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
          
          
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            context = this;
            initView();
        }
    
        private void initView() {
          
          
            button = (Button) findViewById(R.id.button);
    
            button.setOnClickListener(new View.OnClickListener() {
          
          
    
                @Override
                public void onClick(View v) {
          
          
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    AlertDialog alertDialog = builder
                            .setTitle("提示")
                            .setMessage("普通对话框")
                            .setNeutralButton("中立", new DialogInterface.OnClickListener() {
          
          
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
          
          
                                    Toast.makeText(context, "中立按钮", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setNegativeButton("否定", new DialogInterface.OnClickListener() {
          
          
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
          
          
                                    Toast.makeText(context, "否定按钮", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          
          
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
          
          
                                    Toast.makeText(context, "确定按钮", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .create();
    
                    alertDialog.show();
                }
            });
        }
    }
    
  4. 运行效果:

    在这里插入图片描述

简单列表对话框

  1. 修改第 1 例中的 MainActivity 文件中的第 34 ~ 58 行,使用以下代码替换:

    final String[] lesson = {
          
           "语文", "数学", "英语", "化学", "生物", "物理", "历史", "地理", "政治", "体育" };
    
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    AlertDialog alertDialog = builder
            .setTitle("高中课程")
            .setItems(lesson, new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    Toast.makeText(context, "你选择了" + lesson[which], Toast.LENGTH_SHORT).show();
                }
            })
            .create();
    
    alertDialog.show();
    
  2. 运行效果:

    在这里插入图片描述

单选列表对话框

  1. 修改第 1 例中的 MainActivity 文件中的第 34 ~ 58 行,使用以下代码替换:

    final String[] lesson = {
          
           "语文", "数学", "英语", "化学", "生物", "物理", "历史", "地理", "政治", "体育" };
    
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    AlertDialog alertDialog = builder
            .setTitle("高中课程")
            .setSingleChoiceItems(lesson, 0, new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    Toast.makeText(context, "你选择了" + lesson[which], Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton("否定", new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    Toast.makeText(context, "否定按钮", Toast.LENGTH_SHORT).show();
                }
            })
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    Toast.makeText(context, "确定按钮", Toast.LENGTH_SHORT).show();
                }
            })
            .create();
    
    alertDialog.show();
    
  2. 运行效果:

    在这里插入图片描述

多选列表对话框

  1. 修改第 1 例中的 MainActivity 文件中的第 34 ~ 58 行,使用以下代码替换:

    final String[] lesson = {
          
           "语文", "数学", "英语", "化学", "生物", "物理", "历史", "地理", "政治", "体育" };
    boolean[] checkedItems = {
          
           true, true, true, false, false, false, false, false, false, true }; // 默认选择
    
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    AlertDialog alertDialog = builder
            .setTitle("高中课程")
            .setMultiChoiceItems(lesson, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
          
          
                    checkedItems[which] = isChecked;
                }
            })
            .setNegativeButton("否定", new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    Toast.makeText(context, "否定按钮", Toast.LENGTH_SHORT).show();
                }
            })
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    StringBuilder results = new StringBuilder();
                    for (int i = 0; i < checkedItems.length; i++) {
          
          
                        if (checkedItems[i]) {
          
          
                            results.append(lesson[i]).append(" ");
                        }
                    }
                    Toast.makeText(context, "你选择:" + results.toString(), Toast.LENGTH_SHORT).show();
                }
            })
            .create();
    
    alertDialog.show();
    
  2. 运行效果:

    在这里插入图片描述

自定义标题和修改确定按钮外边距

  1. 修改第 1 例中的 MainActivity 文件中的第 34 ~ 58 行,使用以下代码替换:

    第 2 ~ 7 行:自定义标题样式
    第 12 行:设置自定义标题
    第 31 ~ 34 行:修改确定(Positive Button)按钮的左边距

    // 自定义标题样式
    TextView title = new TextView(context);
    title.setText("提示");
    title.setPadding(10, 30, 10, 10);
    title.setGravity(Gravity.CENTER); // 居中
    title.setTextSize(18);
    title.setTextColor(Color.BLACK);
    
    // 简单的对话框
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    AlertDialog alertDialog = builder
            .setCustomTitle(title) // 设置自定义标题
            .setMessage("自定义标题和修改确定按钮外边距")
            .setNegativeButton("否定", new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    Toast.makeText(context, "否定按钮", Toast.LENGTH_SHORT).show();
                }
            })
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          
          
                @Override
                public void onClick(DialogInterface dialog, int which) {
          
          
                    Toast.makeText(context, "确定按钮", Toast.LENGTH_SHORT).show();
                }
            })
            .create();
    
    alertDialog.show();
    
    // 修改确定按钮的左边距
    Button buttonPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) buttonPositive.getLayoutParams();
    layoutParams.setMargins(layoutParams.leftMargin + 20, layoutParams.topMargin, layoutParams.rightMargin, layoutParams.bottomMargin); // 外边距
    buttonPositive.setLayoutParams(layoutParams);
    
  2. 运行效果:

    在这里插入图片描述

参考

AlertDialog(对话框)详解

Android修改原生AlertDialog按钮的颜色大小边距位置以及标题居中等

猜你喜欢

转载自blog.csdn.net/qq_29761395/article/details/113426668