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.
AlertDialog generally consists of the main title, the message, and two buttons, technically termed as a positive button and a negative button. Both positive and negative buttons can be programmed to perform various actions. By default, the negative button lets close the AlertDialog without any additional lines of code.
You can do this very easily. AlertDialog. Builder alertDialogBuilder = new AlertDialog. Builder(context); // set title alertDialogBuilder.
AlertDialog. A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout.
Alert Dialog code has three methods:setTitle() method for displaying the Alert Dialog box Title. setMessage() method for displaying the message. setIcon() method is used to set the icon on the Alert dialog box.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With