AlertDialog(对话框)详解

简介: 本节继续给大家带来是显示提示信息的第三个控件AlertDialog(对话框),同时它也是其他Dialog的的父类!比如ProgressDialog,TimePickerDialog等,而AlertDialog的父类是:Dialog!另外,不像前面学习的Toast和Notification,AlertDialog并不能直接new出来,如果你打开AlertDialog的源码,会发现构造方法是protected的,如果我们要创建AlertDialog的话,我们需要使用到该类中的一个静态内部类:public static class Builder,然后来调用AlertDialog里的相关方法,来对A

本节继续给大家带来是显示提示信息的第三个控件AlertDialog(对话框),同时它也是其他Dialog的的父类!比如ProgressDialog,TimePickerDialog等,而AlertDialog的父类是:Dialog!另外,不像前面学习的Toast和Notification,AlertDialog并不能直接new出来,如果你打开AlertDialog的源码,会发现构造方法是protected的,如果我们要创建AlertDialog的话,我们需要使用到该类中的一个静态内部类:public static class Builder,然后来调用AlertDialog里的相关方法,来对AlertDialog进行定制,最后调用show()方法来显示我们的AlertDialog对话框!

1.基本使用流程

  • Step 1:创建AlertDialog.Builder对象;
  • Step 2:调用setIcon()设置图标,setTitle()setCustomTitle()设置标题;
  • Step 3:设置对话框的内容:setMessage()还有其他方法来指定显示的内容;
  • Step 4:调用setPositive/Negative/NeutralButton()设置:确定,取消,中立按钮;
  • Step 5:调用create()方法创建这个对象,再调用show()方法将对话框显示出来;

2.几种常用的对话框使用示例

运行效果图:

网络异常,图片无法展示
|

核心代码

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_dialog_one;
    private Button btn_dialog_two;
    private Button btn_dialog_three;
    private Button btn_dialog_four;
    private Context mContext;
    private boolean[] checkItems;
    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        bindView();
    }
    private void bindView() {
        btn_dialog_one = (Button) findViewById(R.id.btn_dialog_one);
        btn_dialog_two = (Button) findViewById(R.id.btn_dialog_two);
        btn_dialog_three = (Button) findViewById(R.id.btn_dialog_three);
        btn_dialog_four = (Button) findViewById(R.id.btn_dialog_four);
        btn_dialog_one.setOnClickListener(this);
        btn_dialog_two.setOnClickListener(this);
        btn_dialog_three.setOnClickListener(this);
        btn_dialog_four.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //普通对话框
            case R.id.btn_dialog_one:
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("系统提示:")
                        .setMessage("这是一个最普通的AlertDialog,\n带有三个按钮,分别是取消,中立和确定")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "你点击了取消按钮~", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "你点击了确定按钮~", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNeutralButton("中立", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "你点击了中立按钮~", Toast.LENGTH_SHORT).show();
                            }
                        }).create();             //创建AlertDialog对象
                alert.show();                    //显示对话框
                break;
            //普通列表对话框
            case R.id.btn_dialog_two:
                final String[] lesson = new String[]{"语文", "数学", "英语", "化学", "生物", "物理", "体育"};
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("选择你喜欢的课程")
                        .setItems(lesson, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(), "你选择了" + lesson[which], Toast.LENGTH_SHORT).show();
                            }
                        }).create();
                alert.show();
                break;
            //单选列表对话框
            case R.id.btn_dialog_three:
                final String[] fruits = new String[]{"苹果", "雪梨", "香蕉", "葡萄", "西瓜"};
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("选择你喜欢的水果,只能选一个哦~")
                        .setSingleChoiceItems(fruits, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(), "你选择了" + fruits[which], Toast.LENGTH_SHORT).show();
                            }
                        }).create();
                alert.show();
                break;
            //多选列表对话框
            case R.id.btn_dialog_four:
                final String[] menu = new String[]{"水煮豆腐", "萝卜牛腩", "酱油鸡", "胡椒猪肚鸡"};
                //定义一个用来记录个列表项状态的boolean数组
                checkItems = new boolean[]{false, false, false, false};
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setMultiChoiceItems(menu, checkItems, new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                checkItems[which] = isChecked;
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String result = "";
                                for (int i = 0; i < checkItems.length; i++) {
                                    if (checkItems[i])
                                        result += menu[i] + " ";
                                }
                                Toast.makeText(getApplicationContext(), "客官你点了:" + result, Toast.LENGTH_SHORT).show();
                            }
                        })
                        .create();
                alert.show();
                break;
        }
    }
}

布局就是四个简单的按钮,这里就不贴出来了,用法非常简单~无非就是创建一个Builder对象后,进行相关设置,然后create()生成一个AlertDialog对象,最后调用show()方法将AlertDialog显示出来而已!另外,细心的你可能发现我们点击对话框的外部区域,对话框就会消失,我们可以为builder设置setCancelable(false)即可解决这个问题!

3.通过Builder的setView()定制显示的AlertDialog

我们可以自定义一个与系统对话框不同的布局,然后调用setView()将我们的布局加载到AlertDialog上,上面我们来实现这个效果:

运行效果图

网络异常,图片无法展示
|

关键代码

首先是两种不同按钮的selctor的drawable文件:

btn_selctor_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@mipmap/iv_icon_exit_pressed"/>
    <item android:drawable="@mipmap/iv_icon_exit_normal"/>
</selector>

btn_selctor_choose.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@mipmap/bg_btn_pressed"/>
    <item android:drawable="@mipmap/bg_btn_normal"/>
</selector>

接着是自定义的Dialog布局:view_dialog_custom.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/titlelayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="#53CC66"
        android:padding="5dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="提示信息"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:textStyle="bold" />
        <Button
            android:id="@+id/btn_cancle"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:background="@drawable/btn_selctor_exit" />
    </RelativeLayout>
    <LinearLayout
        android:id="@+id/ly_detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/titlelayout"
        android:layout_centerInParent="true"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:text="通过setView()方法定制AlertDialog"
            android:textColor="#04AEDA"
            android:textSize="18sp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="作者:Coder-pig"
            android:textColor="#04AEDA"
            android:textSize="18sp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ly_detail"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_blog"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:background="@drawable/btn_selctor_choose"
            android:text="访问博客"
            android:textColor="#ffffff"
            android:textSize="20sp" />
        <Button
            android:id="@+id/btn_close"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:background="@drawable/btn_selctor_choose"
            android:text="关闭"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>
</RelativeLayout>

最后是MainActivity.java

public class MainActivity extends AppCompatActivity {
    private Button btn_show;
    private View view_custom;
    private Context mContext;
    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        btn_show = (Button) findViewById(R.id.btn_show);
        //初始化Builder
        builder = new AlertDialog.Builder(mContext);
        //加载自定义的那个View,同时设置下
        final LayoutInflater inflater = MainActivity.this.getLayoutInflater();
        view_custom = inflater.inflate(R.layout.view_dialog_custom, null,false);
        builder.setView(view_custom);
        builder.setCancelable(false);
        alert = builder.create();
        view_custom.findViewById(R.id.btn_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });
        view_custom.findViewById(R.id.btn_blog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "访问博客", Toast.LENGTH_SHORT).show();
                Uri uri = Uri.parse("http://blog.csdn.net/coder_pig");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                alert.dismiss();
            }
        });
        view_custom.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "对话框已关闭~", Toast.LENGTH_SHORT).show();
                alert.dismiss();
            }
        });
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.show();
            }
        });
    }
}
相关文章
|
9月前
|
算法 Java 调度
java并发编程中Monitor里的waitSet和EntryList都是做什么的
在Java并发编程中,Monitor内部包含两个重要队列:等待集(Wait Set)和入口列表(Entry List)。Wait Set用于线程的条件等待和协作,线程调用`wait()`后进入此集合,通过`notify()`或`notifyAll()`唤醒。Entry List则管理锁的竞争,未能获取锁的线程在此排队,等待锁释放后重新竞争。理解两者区别有助于设计高效的多线程程序。 - **Wait Set**:线程调用`wait()`后进入,等待条件满足被唤醒,需重新竞争锁。 - **Entry List**:多个线程竞争锁时,未获锁的线程在此排队,等待锁释放后获取锁继续执行。
216 12
|
消息中间件 数据库
TCC(Try-Confirm-Cancel)
【6月更文挑战第5天】
617 3
|
11月前
|
Java Spring
无法自动装配。找不到 ‘Service‘ 类型的 Bean。 Service 与 ServiceImpl 没有互相联系起来
文章讲述了一个Java开发中的问题,即Spring框架无法自动装配Bean,原因是ServiceImpl类未实现对应的Service接口,解决办法是让ServiceImpl实现Service接口。
1820 0
无法自动装配。找不到 ‘Service‘ 类型的 Bean。 Service 与 ServiceImpl 没有互相联系起来
|
12月前
|
监控 物联网 开发者
物联网卡使用过程中常见问题
在物联网(IoT)应用中,用户或开发者可能会遇到一些常见问题。以下是一些物联网卡应用中常用问题及其操作建议:
|
6月前
|
SQL 存储 数据库
【赵渝强老师】达梦数据库的归档模式
本文介绍了达梦数据库备份与恢复中重做日志文件的作用,重点讲解了归档模式的必要性及其配置方法。文章分析了非归档模式可能导致的数据丢失问题,并推荐使用归档模式以保障数据一致性和完整性。归档模式分为本地归档和远程归档:本地归档将重做日志存储在本地,而远程归档适用于集群环境,确保所有节点拥有完整日志。文中还详细展示了如何通过SQL命令开启归档模式,包括切换状态、设置路径及验证配置等步骤,并附有视频教程辅助理解。
312 1
|
机器学习/深度学习 人工智能 算法
【AI伦理与社会责任】讨论人工智能在隐私保护、偏见消除、自动化对就业的影响等伦理和社会问题。
人工智能(AI)作为第四次产业革命的核心技术,在推动社会进步和经济发展的同时,也引发了一系列伦理和社会问题。以下从隐私保护、偏见消除以及自动化对就业的影响三个方面进行详细讨论。
341 2
|
小程序 前端开发
微信综合购物商城小程序ui模板源码
微信电商小程序前端页面,综合购物商城ui界面模板。主要功能包含:电商主页、商品分类、购物车、购物车结算、我的个人中心管理、礼券、签到、新人专享、专栏、商品详情页、我的订单、我的余额、我的积分、我的收藏、我的地址、我的礼券等。这是一款非常齐全的电商小程序前端模板。
412 4
|
SQL 数据库 索引
数据库中表维护
【5月更文挑战第7天】本文介绍了提高数据库性能的五个技巧。1) 使用`ON DUPLICATE KEY UPDATE`或`ON CONFLICT DO UPDATE`避免锁竞争,尤其在高并发更新计数器场景下。2) 通过JOIN查询进行基于选择的更新。3) 使用公式表达式-CTE-删除重复行 。4) 定期运行`ANALYZE`命令更新表统计信息。这些方法有助于优化数据库性能,减少锁等待和提高查询速度。
194 1
数据库中表维护
|
编译器 开发工具 git
下载、安装代码版本管理软件Git并复制GitHub代码
本文介绍分布式开源版本控制系统Git的下载、安装,并基于Git实现克隆GitHub中项目代码的方法~
286 1
下载、安装代码版本管理软件Git并复制GitHub代码
|
设计模式 自然语言处理 Java
递归下降解析器的设计与实现
递归下降解析器的设计与实现

热门文章

最新文章