Reputation: 6258
In my Android application, in order to ask the user if he/she wants to resume a current game, I display a dialog saying "Do you want to resume current game? Yes - No" on the main game activity.
The thing is that if I resume various times this activity without answering the dialog, then I get several dialogs, on top of each other, which is obviously not my goal.
I could easily avoid this behavior using a Boolean var, but I was wondering if the Dialog class had a kind of option preventing to be duplicated or something of the kind.
Upvotes: 11
Views: 17312
Reputation: 19
Check Dialog already showing or not
private Dialog mDialog;
private void showDialog(String title, String message) {
//stop multiple dialog window
if(dialog != null && dialog.isShowing()) {
return;
}
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message);
dialog = dialogBuilder.show();
}
Upvotes: 1
Reputation: 299
I also encountered such a problem when I tried to override the onDismiss()
method without super.onDismiss(dialog);
It turns out I deleted super.onDismiss(dialog)
and because of this, the dialogs were duplicated
Back added, the error disappeared.
I hope someone will help
Upvotes: 2
Reputation: 327
Use isAdded() method,
Kotlin example:
view.button.setOnClickListener({
if (!dialog.isAdded) {
dialogShow(dialog)
}
})
and somewhere in the fragment or activity
private fun dialogShow(dialog: DialogFragment?) {
val fragmentManager: FragmentManager = (context as MyActivity).fragmentManager
dialog?.show( fragmentManager,TAG)
}
Upvotes: 0
Reputation: 405
private Dialog mDialog;
private void showDialog(String title, String message) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message);
// Dismiss any old dialog.
if (mDialog != null) {
mDialog.dismiss();
}
// Show the new dialog.
mDialog = dialogBuilder.show();
}
Upvotes: 5
Reputation: 85
Rather then doing hacks or using booleans you can use the method given by google itself
public boolean isShowing ()
it Returns a boolean value Whether the dialog is currently showing.
Upvotes: 4
Reputation: 59168
You can use singleton pattern, could be roughly like this:
Dialog myDialog = null;
public void showDialog() {
if(myDialog == null) {
/* show your dialog here... */
myDialog = ...
}
}
public void hideDialog() {
if(myDialog != null) {
/* hide your dialog here... */
myDialog = null;
}
}
Upvotes: 8