Reputation: 22138
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.
Upvotes: 42
Views: 78318
Reputation: 6961
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.
Upvotes: 0
Reputation: 3735
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).
Upvotes: 7
Reputation: 51411
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();
Upvotes: 16
Reputation: 1319
dialog.dismiss();
Only this line will close it. :-)
Implement it in the onClickListener.
Upvotes: 9