简体   繁体   English

如何以编程方式删除AlertDialog

[英]How to remove AlertDialog programmatically

In an android application, I'm showing to the user an AlertDialog with no buttons, just a message. 在Android应用程序中,我向用户显示没有按钮的AlertDialog,只显示一条消息。 How can I destroy the AlertDialog programmatically so that it's not visible anymore? 如何以编程方式销毁AlertDialog以使其不再可见? I tried with cancel() and dismiss() but they are not working, the view remains there. 我尝试使用cancel()和dismiss(),但它们不工作,视图仍然存在。

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

then I tried 然后我试了

test.show().cancel() and test.show().cancel()

test.show().dismiss()

but not working. 但没有工作。

You should refer to the AlertDialog itself, not the builder. 您应该参考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
AlertDialog.Builder test = new AlertDialog.Builder(context);
...

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

Later you want to hide it: 以后你想隐藏它:

 dialog.dismiss();

add this alertDialog.setCanceledOnTouchOutside(true); 添加此alertDialog.setCanceledOnTouchOutside(true); to dismiss dialog if user touch outside 如果用户在外面触摸,则关闭对话框

OR by click Device back button 或者单击“设备返回”按钮

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;
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM