Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a Dialog in Android programmatically?

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.

like image 367
Amir Hossein Ghasemi Avatar asked Aug 08 '13 21:08

Amir Hossein Ghasemi


People also ask

How do you dismiss material dialog?

setCancelable(false); AlertDialog dialog = builder. show(); In order to dismiss the dialog, you can call dismiss function like this.

How do I turn off custom dialog?

You may call dismiss(); on the dialog. This work for me.

How do I dismiss all dialogs in Android?

I use onCreateDialog(int id) to create each dialog and I use showDialog(int id) and dismissDialog(int id) method show and dismiss each dialog respectively.

What is AlertDialog builder in Android?

Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response the next step is processed. Android Alert Dialog is built with the use of three fields: Title, Message area, Action Button.


2 Answers

You can call dismiss on the dialog.

like image 183
iagreen Avatar answered Sep 28 '22 08:09

iagreen


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(); 
like image 41
Philipp Jahoda Avatar answered Sep 28 '22 08:09

Philipp Jahoda