【问题标题】:Dismiss alert dialog builder from onpause从 onpause 中关闭警报对话框生成器
【发布时间】:2013-06-17 01:47:30
【问题描述】:

我正在使用以下代码来显示一个带有两个按钮的警报对话框。但是,如果在活动暂停时没有取消对话框,则会引发错误。我知道您可以使用 .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();

【问题讨论】:

  • dialog.cancel 怎么样?

标签: android


【解决方案1】:

显示对话框时可以得到AlertDialog:

dialog = alertDialog.show(); // show and return the dialog

然后在 onPause 中你可以关闭 AlertDialog:

@Override
protected void onPause() {
    super.onPause();
    if (dialog != null) {
        dialog.dismiss();
    }
}

对话框需要定义为实例变量才能工作:

private AlertDialog dialog; // instance variable

顺便说一句,AlertDialog.Builder 是一个构建器,因为您可以像这样使用builder pattern

dialog = AlertDialog.Builder(MyActivity.this)
    .setTitle("Title");
    .setMessage("Message")
[...]
    .show();

【讨论】:

  • 我发现这对我不起作用,因为 alertDialog.show();返回 void 而不是预期的 AlertDialog。不过还是谢谢。
  • 这个答案正是原始问题所说的不起作用。 AlertDialog 并不总是一个选项,因此 AlertDialog.Builder 是替代方案;但是,此答案不适用于 AlertDialog.Builder。
  • @Rodrigo Mesquita 您没有阅读答案。我的回答是,当您显示来自 AlertDialog.Builder 的对话框时,您会得到 AlertDialog。获得 AlertDialog 后,您可以关闭该对话框。无法关闭 AlertDialog.Builder。您提到的链接完全符合我在回答中的描述。这是公认的答案这一事实可能表明它回答了 OP 的问题。
  • @EmanuelMoecklin,几天后我再次查看了您的答案和我的答案,但我仍然认为这有点令人困惑,因为您两次初始化了“对话”对象。您在“BTW”部分下方写的内容对我有用,但顶部确实让我感到困惑。这是公认的答案这一事实仅意味着有些人理解它,但不是所有人。我认为如果您尝试简化它,您可以获得更多选票。
  • 我没有初始化两次。它是公认的答案这一事实与人们理解它无关,而是与它回答操作员的问题有关(尽管赞成票确实如此)。一旦我在电脑前,我会澄清答案。
猜你喜欢
  • 2017-07-21
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
相关资源
最近更新 更多