Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show only one Dialog at a time?

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();
    }
});
like image 353
Asha Soman Avatar asked Sep 24 '12 07:09

Asha Soman


3 Answers

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();
  }
like image 110
Ram Avatar answered Nov 17 '22 02:11

Ram


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.

like image 32
user387184 Avatar answered Nov 17 '22 04:11

user387184


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();
}
like image 38
Araw Avatar answered Nov 17 '22 04:11

Araw