Android基础入门教程——2.5.3 AlertDialog(对话框)详解

标签(空格分隔): Android基础入门教程


本节引言:

本节继续给大家带来是显示提示信息的第三个控件AlertDialog(对话框),同时它也是其他
Dialog的的父类!比如ProgressDialog,TimePickerDialog等,而AlertDialog的父类是:Dialog!
另外,不像前面学习的Toast和Notification,AlertDialog并不能直接new出来,如果你打开
AlertDialog的源码,会发现构造方法是protected的,如果我们要创建AlertDialog的话,我们
需要使用到该类中的一个静态内部类:public static class Builder,然后来调用AlertDialog
里的相关方法,来对AlertDialog进行定制,最后调用show()方法来显示我们的AlertDialog对话框!
好的,下面我们就来学习AlertDialog的基本用法,以及定制我们的AlertDialog!
官方文档: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;@Overrideprotected 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);}@Overridepublic 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() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(mContext, "你点击了取消按钮~", Toast.LENGTH_SHORT).show();}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(mContext, "你点击了确定按钮~", Toast.LENGTH_SHORT).show();}}).setNeutralButton("中立", new DialogInterface.OnClickListener() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {checkItems[which] = isChecked;}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic 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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mContext = MainActivity.this;btn_show = (Button) findViewById(R.id.btn_show);//初始化Builderbuilder = 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() {@Overridepublic void onClick(View v) {alert.dismiss();}});view_custom.findViewById(R.id.btn_blog).setOnClickListener(new View.OnClickListener() {@Overridepublic 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() {@Overridepublic void onClick(View v) {Toast.makeText(getApplicationContext(), "对话框已关闭~", Toast.LENGTH_SHORT).show();alert.dismiss();}});btn_show.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {alert.show();}});}
}

4.示例代码下载

AlertDialogDemo.zip
AlertDialogDemo1.zip


本节小结:

好的,本节给大家介绍了一下AlertDialog的基本使用,写了几个调用AlertDialog的例子,
最后还通过setView方法自定义了一下我们的AlertDialog!是不是还意犹未尽呢?但这说不上
真正的自定义控件,我们把自定义控件放到进阶系列,到时后会有个专题来和大家探讨
下自定义控件~敬请期待~就说这么多,谢谢~

Android基础入门教程——2.5.3 AlertDialog(对话框)详解相关推荐

  1. Android基础入门教程——8.3.18 Canvas API详解(Part 3)Matrix和drawBitmapMash

    Android基础入门教程--8.3.18 Canvas API详解(Part 3)Matrix和drawBitmapMash 标签(空格分隔): Android基础入门教程 本节引言: 在Canva ...

  2. 最新Android基础入门教程目录(完结版)

    第一章:环境搭建与开发相关(已完结 10/10) https://blog.csdn.net/coder_pig/article/details/50000773 Android基础入门教程--1.1 ...

  3. 2015年最新Android基础入门教程目录(完结版)

    2015年最新Android基础入门教程目录(完结版) 标签(空格分隔): Android基础入门教程 前言: 关于<2015年最新Android基础入门教程目录>终于在今天落下了帷幕,全 ...

  4. android 编辑9图片,Android基础入门教程——1.6 .9(九妹)图片怎么玩

    Android基础入门教程--1.6 .9(九妹)图片怎么玩 Android基础入门教程 1.本节引言: 可能有的一些疑问: 1.什么是.9图片? 答:图片后缀名前有.9的图片,如pic1.9.png ...

  5. android设置webview缓存目录,Android基础入门教程——7.5.5 WebView缓存问题

    Android基础入门教程--7.5.5 WebView缓存问题 Android基础入门教程 本节引言:现在很多门户类信息网站,比如虎嗅,ifanr,钛媒体等等的APP,简单点说是信息阅读类的APP, ...

  6. Android基础入门教程——4.3.1 BroadcastReceiver牛刀小试

    Android基础入门教程--4.3.1 BroadcastReceiver牛刀小试 标签(空格分隔): Android基础入门教程 本节引言 本节我们将来学习Android四大组件中的第三个:Bro ...

  7. Android基础入门教程——10.1 TelephonyManager(电话管理器)

    Android基础入门教程--10.1 TelephonyManager(电话管理器) 标签(空格分隔): Android基础入门教程 本节引言: 本章节是Android基础入门教程的最后一章,主要讲 ...

  8. Android基础入门教程——7.6.1 Socket学习网络基础准备

    Android基础入门教程--7.6.1 Socket学习网络基础准备 标签(空格分隔): Android基础入门教程 本节引言: 为了照顾没学过Java Socket的初学者,或者说捋一捋Andro ...

  9. Android基础入门教程——1.7 界面原型设计

    Android基础入门教程--1.7 界面原型设计 标签(空格分隔): Android基础入门教程 本节引言: 引用锤子科技视觉设计总监--罗子雄在重庆TEDx活动上说的一小段话: 每当我们看到一些美 ...

最新文章

  1. DeeCamp 2020启动,邀请全球AI菁英共克世界变局下真实难题!
  2. 在python中、列表中的元素可以是_在Python中存储一个列表的元素,在另一个列表中 – 通过引用?...
  3. 情怀java手机网游_经典端游移植手游 “情怀”赋予老IP全新活力
  4. [答疑]-ATF中异常向量表为何没有实现“Current Exception level with SP_ELx, x>0.“
  5. Teams Bot开发系列:Activity处理流程
  6. 7-2 单源最短路径 (10 分)(思路+详解+邻接表做法)Come Brather!!!!!!!!!!
  7. Python的Wiki
  8. PAT甲题题解-1070. Mooncake (25)-排序,大水题
  9. Log4j2 杀不死 Java
  10. 12 个学习新的编程语言的方法
  11. synchronized互斥锁结合wait()、notify()方法使用,实现线程的阻塞以及线程调用案例
  12. 浅谈:字符串、时间格式的转换
  13. CentOs下安装pip3
  14. android 多张图片渐变切换控件
  15. 计算机课学生评价用语,主题班会课对学生的评价用语
  16. 线程的条件变量(cond)
  17. 【华为OD机试真题 Python】判断字符串子序列
  18. php执行shell脚本
  19. AOP注解和切入点表达式
  20. 以太坊实践经验之《eth.blockNumber结果为0》

热门文章

  1. nginx部署vue项目路径添加前缀
  2. 如何保护个人信息隐私
  3. word2007不显示“审阅”选项卡
  4. python3安装PIL库的经历
  5. AMD CPU Ryzen R7 2700X 安装 Ubuntu18.04 + AMD RX580 显卡驱动
  6. Au音频效果参考:生成
  7. 多玩LOL盒子 3.5.1
  8. 21点游戏简单开发(Python)
  9. Java 输出左直角三角形
  10. cf进游戏黑屏显示服务器已满,《CFHD》游戏黑屏解决办法