【问题标题】:How to remove AlertDialog programmatically如何以编程方式删除 AlertDialog
【发布时间】:2017-04-19 15:30:15
【问题描述】:

在一个 android 应用程序中,我向用户显示一个没有按钮的 AlertDialog,只是一条消息。如何以编程方式销毁 AlertDialog 使其不再可见?我尝试使用 cancel() 和 dismiss() 但它们不起作用,视图仍然存在。

AlertDialog.Builder test = new AlertDialog.Builder(context);
test.setTitle("title");
test.setCancelable(true);
test.setMessage("message...");
test.create().show();

然后我尝试了

test.show().cancel()

test.show().dismiss()

但不工作。

【问题讨论】:

标签: android android-alertdialog


【解决方案1】:

您应该参考 AlertDialog 本身,而不是构建器。

AlertDialog.Builder test = new AlertDialog.Builder(context);
test.setTitle("title");
test.setCancelable(true);
test.setMessage("message...");
ALertDialog testDialog = test.create();
testDialog.show();  // to show
testDialog.dismiss();  // to dismiss

【讨论】:

  • 我喜欢你的回答。它按预期工作! :) 谢谢。
【解决方案2】:
AlertDialog.Builder test = new AlertDialog.Builder(context);
...

AlertDialog dialog = test.create().show();

稍后你想隐藏它:

 dialog.dismiss();

【讨论】:

    【解决方案3】:

    添加此alertDialog.setCanceledOnTouchOutside(true); 以在用户触摸外部时关闭对话框

    或者通过点击设备返回按钮

    alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                alertDialog.dismiss();
                return true;
            }
            return false;
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 2013-12-22
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      相关资源
      最近更新 更多