3

how to check if my alert is already showing on screen ?

 AlertDialog.Builder alert = new AlertDialog.Builder(this);

 alert.show();

I can maintain state by adding a flag in my code to set and reset, but if there is already a method that I can re use ?

3
  • Please be clear. Do you want to check if alert is currently being shown? Oct 22, 2014 at 5:46
  • yes exactly @MysticMagic Oct 22, 2014 at 5:47
  • alert.isShowing() method.
    – Rustam
    Oct 22, 2014 at 5:51

4 Answers 4

12

There is no isShowing() method on the AlertDialog.Builder class. There is one on the Dialog class though.

AlertDialog.Builder

Dialog

An AlertDialog.Builder is used to create an AlertDialog. Once you have an instance of an AlertDialog, you can determine whether or not it is still showing by then calling isShowing() on it.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
AlertDialog alertDialog = alertDialogBuilder.create();

if(!alertDialog.isShowing()){   
  //if its visibility is not showing then show here 
   alertDialog.show();       
 }else{
  //do something here... if already showing       
  }
3

Yes you can check it with isShowing(); method it's documented in the Android Documentation too

But in your case you need to catch the AlertDialog that build by the AlertDialog.Builder first.
so your code should be like this

AlertDialog alertDialog;

function showDialog() {
    if(alertDialog == null) { 
        //Initial Creation will always show 
        //or you can just use create() if you don't want to show it at initial creation
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        AlertDialog alertDialog = alert.show();
    else {
        if(alertDialog.isShowing()) {
             alertDialog.hide();
        } else {
             alertDialog.show();
        }
    }
}
1
  • 1
    but I want to decide weather to show or not based on its visiblity, can I do it before invoking show() ? Oct 22, 2014 at 5:52
2

Use this:

AlertDialog alertDialog = alert.create();

//to check if its being shown
if(!alertDialog.isShowing()){
    //do something
    alertDialog.show();
}

It will return true if currently that alert dialog is being shown. So in your case, check if it returns false, and then show it.

Hope it helps.

0

You can use isShowing method of dialog or you can maintain flag like when you create alert dialog flag is 0 and after showing make it 1.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.