How Do You Disable A Button Inside Of An Alertdialog?
I am trying to write an AlertDialog with 3 buttons. I want the middle, Neutral Button to be disabled if a certain condition is not met. Code int playerint = settings.getPlayerInt()
Solution 1:
You can't call getButton()
on the AlertDialog.Builder
. It has to be called on the resulting AlertDialog
after creation. In other words
AlertDialog.Builderalertbox=newAlertDialog.Builder(this);
//...All your code to set up the buttons initiallyAlertDialogdialog= alertbox.create();
Buttonbutton= dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
The builder is just a class to make constructing the dialog easier...it isn't the actual dialog itself.
HTH
Solution 2:
Better solution in my opinion:
AlertDialog.Builderbuilder=newAlertDialog.Builder(context);
builder.setPositiveButton("Positive", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int whichButton) {
// some code
}
});
AlertDialogalertDialog= builder.create();
alertDialog.setOnShowListener(newDialogInterface.OnShowListener() {
@OverridepublicvoidonShow(DialogInterface dialog) {
if(**some condition**)
{
Buttonbutton= alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
if (button != null) {
button.setEnabled(false);
}
}
}
});
Solution 3:
The trick is that you need to use the AlertDialog
object retuned by AlertDialog.Builder.show()
method. No need to call AlertDialog.Builder.create()
.
Example:
AlertDialogdialog= alertbox.show();
if(monsterint > playerint) {
Buttonbutton= dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
button.setEnabled(false);
}
Post a Comment for "How Do You Disable A Button Inside Of An Alertdialog?"