Kneed Kneed - 1 year ago 180
Android Question

Android Dialog, keep dialog open when button is pressed

I would like to keep my dialog open when I press a button.
At the moment it's closing.

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

builder.setMessage("Are you sure you want to exit?")

.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AlertDialog alert = builder.create();

Answer Source

Yes, you can. You basically need to:

  1. Create the dialog with DialogBuilder
  2. show() the dialog
  3. Find the buttons in the dialog shown and override their onClickListener

So, create a listener class:

class CustomListener implements View.OnClickListener {
  private final Dialog dialog;

  public CustomListener(Dialog dialog) {
    this.dialog = dialog;

  public void onClick(View v) {

    // Do whatever you want here

    // If you want to close the dialog, uncomment the line below

Then when showing the dialog use:

AlertDialog dialog = dialogBuilder.create();;
Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));

Remember, you need to show the dialog otherwise the button will not be findable. Also, be sure to change DialogInterface.BUTTON_POSITIVE to whatever value you used to add the button. Also note that when adding the buttons in the DialogBuilder you will need to provide onClickListeners - you can not add the custom listener in there, though - the dialog will still dismiss if you do not override the listeners after show() is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download