My Android application shows an AlertDialog on a button click. When I click on the button more than once more than one Dialog is created. How can I fix this?
Here is my code:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = new AlertDialog.Builder(context);
dialog.show();
}
});
you need to check if dialog isShowing or not
Dialog has an isShowing() method that should return if the dialog is currently visible.
public AlertDialog myDialog;
public void showDialog(Context context) {
if( myDialog != null && myDialog.isShowing() ) return;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}});
builder.setCancelable(false);
myDialog = builder.create();
myDialog.show();
}
For every push on the button you call the method. So this is why it is shown multile times.
The easiest way is to just define an instance variable in your class of your code like:
boolean alertIsBeingShown = false;
Then set it to true when the alert is being shown like this
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (alertIsBeingShown) return;
alertIsBeingShown = true;
dialog = new AlertDialog.Builder(context);
dialog.show();
}
});
and set the variable to false in the code where you press the OK to make it disappear.
You can create a global flag (boolean) that is set to true if a dialog is shown? If the user click ok, yes, no or anything the dialog is closed and you set the flag to false.
So something like:
boolean dialogShown;
If(dialogShown)
{
return;
}
else
{
dialogShown = true;
dialog = new AlertDialog.Builder(context);
dialog.show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With