Nadir
Nadir

Reputation: 509

How to remove AlertDialog programmatically

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.

Upvotes: 21

Views: 17737

Answers (3)

ZeroOne
ZeroOne

Reputation: 9117

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

Upvotes: 0

azizbekian
azizbekian

Reputation: 62189

AlertDialog.Builder test = new AlertDialog.Builder(context);
...

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

Later you want to hide it:

 dialog.dismiss();

Upvotes: 7

tingyik90
tingyik90

Reputation: 1711

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

Upvotes: 39

Related Questions