gpt4 book ai didi

android - 从 onpause 中关闭警报对话框生成器

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:27:08 26 4
gpt4 key购买 nike

我正在使用以下代码来显示带有两个按钮的警告对话框。但是,如果在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com