前面提到过Activity对dialog的管理有两个回调函数onCreateDialog(int) 和onPrepareDialog(int, Dialog) ,使用步骤:首先需要给不同的Dialog定义不同的id号,通过onCreateDialog(int)方法传入id号参数来初始化生成不同的dialog,显示不通的dialog时则可以直接调用Activity的showDialog(int)方法根据id号来显示不同的dialog.
Dialog也可以自定义布局,在上面加上一些textview,button等控件,步骤很简单只需要自己定义一个新的xml布局文件,然后生成dialog时,掉用builder的setview()方法指定新的view,当然view和xml之间的转化可以通过下面代码完成:
LayoutInflater li = LayoutInflater.from(this);
View v= li.inflate(R.layout.mypatterndialog, null);
示例代码如下:
public class UIDemo extends Activity implements OnClickListener{
Dialog dialog;
public final int ALERT_DIALOG = 1; //第一步
public final int MYPATTERN_DIALOG = 2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1=(Button)this.findViewById(R.string.button1);
button1.setOnClickListener(this );
}
protected Dialog onCreateDialog(int id) {//重写此方法
switch(id)
{
case ALERT_DIALOG:
dialog= createDialog();//根据不同id生成不同dialog
break;
case MYPATTERN_DIALOG:
dialog = createMyDialog();
break;
}
return dialog;
}
protected void onPrepareDialog(int id, Dialog dialog)
{
}
public Dialog createDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("hellohow");
builder.setPositiveButton(R.string.hello,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("dialog");
}
});
builder.setNegativeButton(R.string.button2,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("ca");
}
});
return builder.create();
}
public Dialog createMyDialog()
{
LayoutInflater li = LayoutInflater.from(this);
View v= li.inflate(R.layout.mypatterndialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("mypattern");
builder.setView(v);
builder.setPositiveButton(R.string.button3,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setTitle("button3 click");
}
});
return builder.create();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
this.showDialog(MYPATTERN_DIALOG);//根据id显示不同的dialog
Log.v("111", "pressed");
}
}