How to dismiss AlertDialog.Builder?

2019-02-07 19:52发布

In the following code below, how do I dismiss the alert box? I don't want to cause a memory leak. I tried the .dismiss() on alertDialog, but that didn't work... Thanks

// User pressed the stop button
public void StopMsg_button_action(View view){
    final EditText password_input = new EditText(this); // create an text input field
    password_input.setHint("Enter Password"); // put a hint in it
    password_input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); // change it to password type

    AlertDialog.Builder alertDialog = new Builder(this); // create an alert box
    alertDialog.setTitle("Enter Password"); // set the title
    alertDialog.setView(password_input);  // insert the password text field in the alert box
    alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { // define the 'OK' button
        public void onClick(DialogInterface dialog, int which) {
             String entered_password = password_input.getText().toString();
             if (entered_password.equals(my_password)) {
                locManager.removeUpdates(locListener); // stop listening for GPS coordinates
                startActivity(new Intent(Emergency_1Activity.this,Main_MenuActivity.class)); // go to main menu
             } else {
                 alert("Incorrect Password");
             }
        } 
    });
    alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() { // define the 'Cancel' button
        public void onClick(DialogInterface dialog, int which) {

        } 
    });
    alertDialog.show(); // show the alert box
}

9条回答
迷人小祖宗
2楼-- · 2019-02-07 20:33

i tried this and worked!

.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               alertDialog.setCancelable(true);
            }
        });
查看更多
Bombasti
3楼-- · 2019-02-07 20:35

You must use this way if you don't want to put any buttons and have custom layout in which you have say textview and you want to dismiss alert dialog upon clicking of that textview:

AlertDialog alertDialog = builder.show();

then check

if(alertDialog != null && alertDialog.isShowing()){
      alertDialog.dismiss();
}

This is also true if you want to dismiss it somewhere else in your activity after checking some condition.

查看更多
萌系小妹纸
4楼-- · 2019-02-07 20:41

Instead of alertDialog.setNeutralButton just use alertDialog.setNegativeButton. Use dialog.cancel(), because dialog.dismiss() is not a method available for Alert dialogs.

查看更多
登录 后发表回答