如果你希望自定义你的对话框, 可以扩展Dialog类.
Showing a Dialog 显示对话框
一个对话框总是被创建和显示为一个Activity的一部分. 你应该在Activity的onCreateDialog(int)中创建对话框. 当你使用这个回调函数时,Android系统自动管理每个对话框的状态并将它们和Activity连接, 将Activity变为对话框的"所有者". 这样,每个对话框从Activity继承一些属性. 例如,当一个对话框打开时, MENU键会显示Activity的菜单, 音量键会调整Activity当前使用的音频流的音量.
* 动态改变对话框值
* 关键点:onPrepareDialog方法 里面调用 removeDialog(id);
* 对话框调用执行顺序 showDialog() -> onCreateDialog() -> onPrepareDialog() -> removeDialog()
* public final boolean showDialog(int id, Bundle args) {
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<ManagedDialog>();
}
ManagedDialog md = mManagedDialogs.get(id);
if (md == null) {
md = new ManagedDialog();
md.mDialog = createDialog(id, null, args);
if (md.mDialog == null) {
return false;
}
mManagedDialogs.put(id, md);
}
md.mArgs = args;
onPrepareDialog(id, md.mDialog, args);
md.mDialog.show();
return true;
}
分析showDialog方法可知
android 创建的Dialog对象统一由ManagedDialogs进行管理,如果想重新执行createDialog()方法,需先将Dialog,移出ManagedDialogs;
public class DialogActivity extends Activity implements OnClickListener {
private static final int DIALOG_SORT_MAILS = 0x1;
public Button mButton;
public boolean flag;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_demo);
LinearLayout layout = (LinearLayout) findViewById(R.id.nextMail);
mButton = new Button(this);
mButton.setText("对话框1");
layout.addView(mButton);
mButton.setOnClickListener(this);
setTitle("动态改变对话框值");
}
@Override
public void onClick(View v) {
showDialog(DIALOG_SORT_MAILS);
}
@Override
public void onPrepareDialog(int id, Dialog dialog) {
Log.d("tag", "onPrepareDialog ");
switch (id) {
case (DIALOG_SORT_MAILS):
Log.d("tag", "removeDialog ");
removeDialog(id);
break;
}
}
@Override
protected Dialog onCreateDialog(int id) {
Log.d("tag", "onCreateDialog ");
AlertDialog.Builder builder = new AlertDialog.Builder(
DialogActivity.this);
switch (id) {
case DIALOG_SORT_MAILS:
builder.setTitle("title");
if (flag) {
flag = false;
mButton.setText("对话框1");
builder.setSingleChoiceItems(R.array.dialog_demo1_entries, 0,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
dialog.cancel();
}
});
} else {
flag = true;
mButton.setText("对话框2");
builder.setSingleChoiceItems(
R.array.dialog_demo2_entries, 0,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
dialog.cancel();
}
});
}
builder.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
break;
}
AlertDialog alert = builder.create();
return alert;
}
}
WindowManager wm = getWindowManager();
Display display = wm.getDefaultDisplay();
LayoutParams lp = dialog.getWindow().getAttributes();