Search code examples
androidandroid-alertdialog

How to dismiss all open Alert Dialogs without any references


I have a restart option in my game. but the problem is that there may be some open alertdialog in the existing activity when I press restart.

When I press restart I want to dismiss all open Alertdialog(if any). I do not have any reference to opened up alertdialogs(Can be o,1 or more than one).

Is there any way I can dismiss all the opened up alertdialogs in the activity at any time without having any reference to it ?


Solution

  • First you could assign all your dialogs to a member variable, e.g.

    private Vector<AlertDialog> dialogs = new Vector<AlertDialog>();
    
    @Override
    protected Dialog onCreateDialog(int id) {
      switch (id) {
        case DIALOG_ALERT:
          Builder builder = new AlertDialog.Builder(this);
          ...
          AlertDialog dialog = builder.create();
          dialogs.add(dialog);
          dialog.show();
       }
       return super.onCreateDialog(id);
    }
    

    Afterwards, you can test whether dialogs are showing or not by using the isShowing() method of your dialogs (check out inherited methods from class android.app.Dialoghttp://developer.android.com/reference/android/app/AlertDialog.html), e.g.

    public void closeDialogs() {
       for (AlertDialog dialog : dialogs)
          if (dialog.isShowing()) dialog.dismiss();
    }
    

    Or you might finish and start your activity again as Pragnani said. Depends on where your restart button is ...