我正在使用以下代码显示带有两个按钮的警告对话框.但是,如果在暂停活动时对话框没有被禁用,则会抛出错误.我知道您可以使用.dismiss关闭对话框,但这是一个AlertDialog Builder而不是Dialog.知道怎么做吗?
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Title");
// Setting Dialog Message
alertDialog.setMessage("Message");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
//yes
dialog.cancel();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//no
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
Run Code Online (Sandbox Code Playgroud)
显示对话框时可以获取AlertDialog:
dialog = alertDialog.show(); // show and return the dialog
Run Code Online (Sandbox Code Playgroud)
然后在onPause中你可以解除AlertDialog:
@Override
protected void onPause() {
super.onPause();
if (dialog != null) {
dialog.dismiss();
}
}
Run Code Online (Sandbox Code Playgroud)
该对话框需要定义为实例变量才能使其工作:
private AlertDialog dialog; // instance variable
BTW AlertDialog.Builder是一个构建器,因为您可以像这样使用构建器模式:
dialog = AlertDialog.Builder(MyActivity.this)
.setTitle("Title");
.setMessage("Message")
[...]
.show();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5627 次 |
| 最近记录: |