How to remove AlertDialog programmatically

13,839

Solution 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

Solution 2

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

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

Later you want to hide it:

 dialog.dismiss();
Share:
13,839

Related videos on Youtube

Nadir
Author by

Nadir

Italian living in Spain and trying to learn the wonderful world of Android developing!

Updated on September 15, 2022

Comments

  • Nadir
    Nadir over 1 year

    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.

  • Ruberandinda Patience
    Ruberandinda Patience almost 5 years
    I like you answer. it works as expected! :) thanks.