昨天我問了這個問題(http://stackoverflow.com/questions/7392321/how-do-you-disable-a-button-inside-of-an-alertdialog)並相應地修改了我的代碼。今天早上,我在模擬器中運行代碼並收到了NPE。下面是代碼:如何禁用AlertDialog中的按鈕?後續問題
public void monster() {
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();
AlertDialog dialog = alertbox.create();
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
}
任何人都知道我做錯了嗎?
@Frank Bozzo我只是表示如何隱藏按鈕:(和我是錯誤的,但梅林是錯誤的'button.setVisibility(View.GONE);' – PedroAGSantos
@FrankBozzo我已經更新了我的答案,並給出了完整的解釋,爲什麼會發生這種情況 – Merlin