本节引言:本节继续给大家带来是显示提示信息的第三个控件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;
@Override
protected 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);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
//普通对话框
case R.id.btn_dialog_one:
alert = null;
builder = new