我昨天问了这个问题(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();
}
});
Run Code Online (Sandbox Code Playgroud)
这就是问题出现的地方
// show the alert box
alertbox.show();
AlertDialog dialog = alertbox.create();
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
}
Run Code Online (Sandbox Code Playgroud)
谁知道我做错了什么?
Dev*_*red 10
你有两个问题.第一个是你应该调用show()
,并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);
}
Run Code Online (Sandbox Code Playgroud)
HTH
归档时间: |
|
查看次数: |
4090 次 |
最近记录: |