这篇文章主要介绍了 Android AlertDialog 对话框用法, 结合实例形式分析了 AlertDialog 对话框的功能及常见使用技巧, 需要的朋友可以参考下
Android 是一种基于 Linux 的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由 Google 公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用 "安卓" 或 "安致"。
本文实例讲述了 Android AlertDialog 对话框用法。分享给大家供大家参考,具体如下:
AlertDialog 对话框的介绍
1、获得 AlertDialog 静态内部类 Buidler 对象,由该类来创建 AlertDialog 对象, 因为 AlertDialog 的构造方法全部是 Protected 类型
2、通过 Buidler 对象设置对话框的标题、按钮以及按钮要响应的事件 DialogInterface.OnClickListener
3、调用 Buidler 的 create() 方法创建对话框
4、调用 AlterDialog 的 show() 方法将内容显示出来
方式一:类似于 html 的 confirm 对话框
- //AlertDialog对话框
- public void createAlertDialog(){
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setMessage("test AlertDialog");
- builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
- }
- });
- builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- Toast.makeText(getApplicationContext(), "删除取消", Toast.LENGTH_SHORT).show();
- }
- });
- builder.create().show();
- }
方式二:像上下文菜单一样设置多个条目选项
- //AlertDialog 设置多个选项的条目或者是单选
- public void createAtherAlertDialog() {
- //由于AlertDialog的构造方法是protected类型,所以不能直接new这个对象,必须依赖AlertDialog.Builder类
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder = builder.setTitle("与菜单类似的Alert");
- String[] array = {
- "烤翅",
- "鲍鱼",
- "熊掌",
- "垃圾"
- };
- boolean[] numbers = {
- false,
- false,
- false,
- false
- };
- //被注释的方式是实现单选
- // builder.setItems(array, new DialogInterface.OnClickListener(){
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // System.out.println(which);
- // }
- // });
- //下面这种方式是实现多选
- builder.setMultiChoiceItems(array, numbers, new DialogInterface.OnMultiChoiceClickListener() {@Override public void onClick(DialogInterface dialog, int which, boolean isChecked) {
- System.out.println("which : " + which + " isChecked : " + isChecked);
- }
- });
- builder.create().show();
- }
希望本文所述对大家 Android 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0324/232629.html