Home » Android » java – How to close a Dialog in Android programmatically?

java – How to close a Dialog in Android programmatically?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:

You can call dismiss on the dialog.

Answer:

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

Answer:

dialog.dismiss();

Only this line will close it. 🙂

Implement it in the onClickListener.

Answer:

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

Answer:

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.