How to close a Dialog in Android programmatically?

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

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


dialog.dismiss();

Only this line will close it. :-)

Implement it in the onClickListener.


You can call dismiss on the dialog.