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();
int monsterint = settings.getMonsterInt();
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("You have Encountered a Monster");
alertbox.setPositiveButton("Fight!",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
createMonster();
fight();
}
});
alertbox.setNeutralButton("Try to Outwit",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
// This should not be static
// createTrivia();
trivia();
}
});
// Return to Last Saved CheckPoint
alertbox.setNegativeButton("Run Away!",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
runAway();
}
});
// show the alert box
alertbox.show();
// Intellect Check
Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
}
The line:
Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);
Gives error:
Cannot cast from AlertDialog.Builder to AlertDialog
How do I fix this?
You can't call getButton()
on the AlertDialog.Builder
. It has to be called on the resulting AlertDialog
after creation. In other words
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
//...All your code to set up the buttons initially
AlertDialog dialog = alertbox.create();
Button button = 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
Better solution in my opinion:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setPositiveButton("Positive", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// some code
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
if(**some condition**)
{
Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
if (button != null) {
button.setEnabled(false);
}
}
}
});
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:
AlertDialog dialog = alertbox.show();
if(monsterint > playerint) {
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
button.setEnabled(false);
}
来源:https://stackoverflow.com/questions/7392321/how-do-you-disable-a-button-inside-of-an-alertdialog