15

How do you disable the positive button of an Android AlertDialog by default?

It appears to be quite normal to want the positive button (In this case "Save") to be disabled before the user has made a change to the view (In this case an EditText.

I know that I can get the button by calling dialog.getButton(DialogInterface.BUTTON_POSITIVE) but this call will return null if show() hasn't been called yet.

Joakim
  • 3,224
  • 3
  • 29
  • 53

2 Answers2

29
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {
        if(condition)
        ((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
});

dialog.show();
rKrishna
  • 1,399
  • 12
  • 22
8

You have to call show() to access alert dialog's buttons. So, just after you call show() on alertDialog, you get the negative button and set it disabled like this:

AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
            .setTitle("Title")
            .setMessage("Message")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert);
    AlertDialog d = builder.show();
    d.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(false);

So, its negative button becomes disabled by default.

yrazlik
  • 10,411
  • 33
  • 99
  • 165