我正在使用以下代码来显示带有两个按钮的警告对话框。但是,如果在 Activity 暂停时对话框未被取消,则会引发错误。我知道您可以使用 .dismiss 关闭对话框,但这是一个 AlertDialog Builder 而不是对话框。知道如何做到这一点吗?
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();
最佳答案
显示对话框时可以得到AlertDialog:
dialog = alertDialog.show(); // show and return the dialog
然后在 onPause 中你可以关闭 AlertDialog:
@Override
protected void onPause() {
super.onPause();
if (dialog != null) {
dialog.dismiss();
}
}
对话框需要定义为实例变量才能工作:
私有(private) AlertDialog 对话框;//实例变量
顺便说一句,AlertDialog.Builder 是一个构建器,因为您可以使用 builder pattern像这样:
dialog = AlertDialog.Builder(MyActivity.this)
.setTitle("Title");
.setMessage("Message")
[...]
.show();
关于android - 从 onpause 中关闭警报对话框生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139428/