对话框在程序中不是必备的,但是用好对话框能对我们编写的应用增色不少。采用对话框可以大大增加应用的友好性。比较常用的背景是:用户登陆、网络正在下载、下载成功或者失败的提示,还有,比如:短信来了、电池没电了等等,只要你想到的,能提高用户体验的,你都可以使用对话框。
今天就来简单介绍一下AlertDialog简单使用吧,
一、Dialog
对话框是在当前界面弹出的一个小窗口,用于显示重要提示信息,提示用户输入信息,确认信息,或者显示某种状态,如下载进度,退出提示等等。一般情况下,用户要与对话框进行交互,然后返回到被只改的界面以继续运行当前的应用程序。
二、Dialog的常用方法
setTitle:为对话框设置标题
setIcon:为对话框设置图标
setMessage:为对话框设置内容
setView:给对话框设置自定义样式
setItems:设置对话框要显示的一个list,一般用于显示几个命令时
setMultiChoiceItems:用来设置对话框显示一系列的复选框
setSingleChoiceItems:设置单选按钮
setNeutralButton:普通按钮
setPositiveButton:给对话框添加“确认”按钮
setNegativeButton:给对话框添加“取消”按钮
下面演示一下确认对话框,单选对话框,多选对话框,列表对话框,自定义对话框的做法。
先上布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.jp.logdemo.MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/toast_common"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/shapemore"
android:text="普通Toast"
android:textSize="15sp" />
<Button
android:id="@+id/toast_seat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/shapemore"
android:text="位置偏移Toast"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/shapemore"
android:text="带图片的Toast"
android:textSize="15sp" />
<Button
android:id="@+id/toast_div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/shapemore"
android:text="自定义的Toast"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width=