基础AlertDialog(提示类控件)
![](https://img.haomeiwen.com/i11686995/ae795e6be94d8281.jpg)
1.什么是AlertDialog
AlertDialog为显示提示信息的第三个控件,一般在程序代码中创建而不在XML文件中创建,同时它也是其他 Dialog的的父类!比如ProgressDialog,TimePickerDialog等,而AlertDialog的父类是:Dialog!
当AlertDialog 出现在界面后,其能够屏蔽掉其他所有控件的交互能力,因此AlertDialog通常用在提示用户、警告信息等场景。
AlertDialog并不能直接new出来,如果你打开 AlertDialog的源码,会发现构造方法是protected的,如果我们要创建AlertDialog的话,我们 需要使用到该类中的一个静态内部类:public static class Builder,调用Builder中的create方法创建AlterDialog对象, 然后来调用AlertDialog 里的相关方法,来对AlertDialog进行定制,最后调用AlterDialog的show()方法来显示我们的AlertDialog对话框!
2.实现AlertDialog的步骤
Step 1:创建AlertDialog.Builder对象;
Step 2:调用setIcon()设置图标,setTitle()或setCustomTitle()设置标题;
Step 3:设置对话框的内容:setMessage()还有其他方法来指定显示的内容;
Step 4:调用setPositive/Negative/NeutralButton()设置:确定,取消,中立按钮;
Step 5:调用create()方法创建这个对象,再调用show()方法将对话框显示出来;
3.日常开发中常用的AlertDialog实例
①普通的AlertDialog
![](https://img.haomeiwen.com/i11686995/1c489060672f11a0.jpg)
![](https://img.haomeiwen.com/i11686995/863fab22568c3614.png)
②带普通列表的AlertDialog
![](https://img.haomeiwen.com/i11686995/dc608fc6baa6b798.jpg)
![](https://img.haomeiwen.com/i11686995/071d632a0b854465.png)
③带单选列表的AlertDialog
![](https://img.haomeiwen.com/i11686995/b8c66a2d0f061af8.jpg)
![](https://img.haomeiwen.com/i11686995/0cdd3fa50429dcf7.png)
④复选框列表的AlertDialog
![](https://img.haomeiwen.com/i11686995/f38eec55d7106b5a.jpg)
![](https://img.haomeiwen.com/i11686995/ed6dad03ad96a004.png)
以上是一些在开发中AlertDialog的常见用法。另外,为了防止点击对话框的外部区域,对话框就会消失,我们 可以为builder设置setCancelable(false)即可解决这个问题!
---------------------------------END-------------------------------