Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if AlertDialog.builder is showing and cancelling it if its showing?

Here is my code -

View layout = LayoutInflater.from(this).inflate(R.layout.dialog_loc_info, null);
final Button mButton_Mobile = (Button) layout.findViewById(R.id.button);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
mButton_Mobile.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        if(builder.)
            showDialog(); // this is another dialog, nothing to do with this code
        }
    });
builder.setNeutralButton(getString(android.R.string.ok),
                         new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
builder.show();
like image 932
Darpan Avatar asked Nov 25 '14 13:11

Darpan


2 Answers

You can use AlertDialog methods for that.

AlertDialog alert = new AlertDialog.Builder(context).create();

if (alert.isShowing()) {
    alert.dismiss();
}

Hope it helps.

like image 70
MysticMagicϡ Avatar answered Oct 26 '22 00:10

MysticMagicϡ


An alternative approach is to use a method to generate the AlertDialog with a builder and then create the AlertDialog without showing it while setting the AlertDialog to a class variable.

Then check with .isShowing(); method

Example:

AlertDialog mAlertDialog;

public showMyAlertDialog(View layout){

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

    builder.setView(layout);

    builder.setNeutralButton(getString(android.R.string.ok),new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            mAlertDialog = null; //setting to null is not required persay
        }

    });

    mAlertDialog = builder.create()
    mAlertDialog.show();
}

public boolean isAlertDialogShowing(AlertDialog thisAlertDialog){
    if(thisAlertDialog != null){
        return thisAlertDialog.isShowing();
    }
}

hope that it is understood how to use this source. cheers

like image 3
CrandellWS Avatar answered Oct 25 '22 22:10

CrandellWS