我们先来了解一下什么是AlertDialog?什么是AlertDialog.Builder?且两者有什么区别?
一个AlertDialog可以有两个以上的Button,可以对一个AlertDialog设置相应的信息。比如title,massage,setSingleChoiceItems,setPositiveButton,setNegativeButton等等。。。。
但不能直接通过AlertDialog的构造函数来生产一个AlertDialog。研究AlertDialog的源码发现AlertDialog所有的构造方法都是写保护的所以不能通过:AlertDialog alertDialog = new AlertDialog();来得到。AlertDialog构造方法源码如下:
- AlertDialog.Builder alertDialog =new AlertDialog.Builder(this);
那就通过一个具体的实例来说说吧(这里用一个最常用的对话框为例):
此时需要关注一个方法setCancelable(false) 该方法定义设置该AlertDialog是否可以被Back键取消,如果不设置默认为true
下面是一些扩展:
根据AlertDialog.Builder 创建 相应的 AlertDialog
- AlertDialog alertDialogs = alertDialog.create();
用dismiss();方法来清除创建过的AlertDialog
- alertDialogs.dismiss();
以上所采用的都是AlertDialog 系统默认的布局 现在说自定义布局的情况 并添加一个用于取消AlertDialog 的 Button
定义其布局 main.xml
- view = this.getLayoutInflater().inflate(R.layout.main, null);
- alertDialog.setView(view);
- alertDialogs= alertDialog.create();
- TextView title = (TextView) view.findViewById(R.id.title);
- title.setTextSize(20);
- title.setTextColor(Color.RED);
- title.setText("Title");
- TextView message = (TextView) view.findViewById(R.id.message);
- message.setText("message");
显示对话框 AlertDialog
- findViewById(R.id.button).setOnClickListener(new OnClickListener(){
- public void onClick(View v) {
- // TODO Auto-generated method stub
- alertDialogs.show();
- }
- });
清除对话框 AlertDialog