我昨天问了这个问题(http://stackoverflow.com/questions/7392321/how-do-you-disable-a-button-inside-of-an-alertdialog)并相应地修改了我的代码......今天早上我跑了模拟器中的代码并收到 NPE。这是代码:
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()
and create()
就这样分开。您实际上所做的是隐式创建一个 AlertDialog 并使用以下命令显示它alertbox.show()
,然后在它的正下方创建第二个AlertDialog
您用来操作按钮的。让我们尽量将对 Builder 的直接调用保持在最低限度。
另外,NPE 崩溃的更直接原因是AlertDialog
着陆按钮本身实际上并没有被创建,直到AlertDialog
准备显示(基本上,之后AlertDialog.show()
再次称为...,不要与AlertDialog.Builder.show()
方法)。为了使用AlertDialog
出于您的目的,您需要在显示对话框后获取并操作按钮状态。这是对最终代码部分的修改,可以修复此问题:
//Create the AlertDialog, and then show it
AlertDialog dialog = alertbox.create();
dialog.show();
//Button is not null after dialog.show()
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
HTH
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)