How to remove AlertDialog programmatically

2019-05-31 16:44发布

问题:

In an android application, I'm showing to the user an AlertDialog with no buttons, just a message. How can I destroy the AlertDialog programmatically so that it's not visible anymore? I tried with cancel() and dismiss() but they are not working, the view remains there.

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().dismiss()

but not working.

回答1:

You should refer to the AlertDialog itself, not the builder.

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

Later you want to hide it:

 dialog.dismiss();


回答3:

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