41

How do I close a Dialog in android programmatically for example by a button?

Imagine I have a Dialog with a OK button on it, and want to close it by OK button, but I cant do that!

I googled and found nothing useful, and almost all of them for closing AlertDialog not a Dialog.

Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
Amir Hossein Ghasemi
  • 20,623
  • 10
  • 57
  • 53

5 Answers5

73

You can call dismiss on the dialog.

iagreen
  • 31,470
  • 8
  • 76
  • 90
  • thank you :) thats worked! sorry about my silly Q :) thanks all :) – Amir Hossein Ghasemi Aug 08 '13 at 21:27
  • I used .setPositiveButton("ok ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dismissDialog(DIALOG_Success); } }) but when I show diaolog again,dialog shows old message.I wrote Activity.this.showDialog(DIALOG_Success,arg); can you help me? – Fatemeh Nov 18 '16 at 08:36
15

This is an example of how to create a AlertDialog with 2 Buttons (OK and cancel). When clicking the cancel button,

dialog.dismiss()

is called to close the dialog.

From anywhere outside, you could call

builder.dismiss();

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("Some message.")
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           // do something
                       }
                   })
                   .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           dialog.dismiss();
                       }
                   });

            builder.show();
Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
  • 11
    there is no such method like builder.dismiss(); – m.zander Jul 19 '16 at 11:41
  • You need to call the `.create()` method on `builder` to have access to `dismiss()`. First do `setNegativeButton(...).create();`, then `builder.dismiss();` – karlingen Apr 03 '23 at 19:25
9
dialog.dismiss();

Only this line will close it. :-)

Implement it in the onClickListener.

Helmisek
  • 1,209
  • 11
  • 12
7

You can use the methods cancel() or dismiss(). The method cancel() essentially the same as calling dismiss(), but it will also call your DialogInterface.OnCancelListener (if registered).

amatellanes
  • 3,645
  • 2
  • 17
  • 19
0

Alternative to the dismiss(); option, if you have your dialog as a separate Activity (s.a. DialogActivity), another way to close it is to call:

   finish();

Call this method inside the OnClickListener class' onClick() method.

This will call the onPause(), onStop() and onDestroy() methods consequently and kill the current activity - same as Back button.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52