在做Android开发的时候经常会遇到需要提醒用户选择或操作的情况,这时候我们可以创建一个AlertDalog来使用。
new AlertDalog.Builder()时可以通过方法链来进行使用,也可以声明AlertDalog变量来接收使用。
一、通过声明一个AlertDalog变量定义对话框(带标题、内容、一个按钮)
<span style="white-space:pre"> </span>private AlertDialog.Builder alertDialog;
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("我是标题");
alertDialog.setMessage("我是内容");
alertDialog.setPositiveButton("确定", null);//第二个参数为事件监听器
alertDialog.show();
二、通过方法链来定义对话框(标题、标题图标、输入框、三个按钮)
<span style="white-space:pre"> </span>new AlertDialog.Builder(this)
.setTitle("请输入")
.setIcon(R.drawable.wifi)
.setView(new EditText(this))//通过setView方法可以自定义显示在对话框中的组件、例如EditText、DatePicker等
.setPositiveButton("确认输入",null)
.setNegativeButton("取消输入",null)
<span style="white-space:pre"> </span>.show();
三、定义三个按钮的对话框
new AlertDialog.Builder(this);
.setTitle("请确定选择");
.setMessage("选择是否或取消");
.setPositiveButton("是", null);
.setNegativeButton("否", null);
.setNeutralButton("取消", null);
.show();
四、单选框
<span style="white-space:pre"> </span>new AlertDialog.Builder(this)
.setTitle("单选框")
.setSingleChoiceItems(new String[]{"选项一", "选项二", "选项三"}, 0, null)
.setNegativeButton("取消选择",null)
.show();
五、多选框
<span style="white-space:pre"> </span>new AlertDialog.Builder(this)
.setTitle("多选框")
.setMultiChoiceItems(new String[]{"多选一","多选二","多选三","多选四"},null,null)
.setPositiveButton("确定选择",null)
.setNegativeButton("取消选择",null)
.show();
六、列表框
<span style="white-space:pre"> </span>new AlertDialog.Builder(this)
.setTitle("列表框")
.setItems(new String[]{"列表一","列表二","列表三"},null)
.show();
| setTitle | 设置标题 |
| setIcon | 设置标题ICO图标 |
| setMessage | 设置内容 |
| setPositiveButton | 设置正向按钮【位于右边】 |
| setNegativeButton | 设置负向按钮【位于左边】 |
| setNeutralButton | 设置中间按钮【位于中间】 |
| setSingleChiceItems | 设置单选框 |
| setMultiChoiceItems | 设置多选框 |
| setItems | 设置列表框 |
| setView | 设置View |
在Android应用开发中,AlertDalog是常见的一种提示用户交互的方式。本文将介绍如何创建和定制AlertDalog,包括设置标题、内容、不同类型的按钮、单选框、多选框以及列表框等,帮助开发者实现丰富的用户提示功能。
468

被折叠的 条评论
为什么被折叠?



