我正在尝试写一个具有3个按钮的AlertDialog.如果不满足某个条件,我想要中间的中性按钮被禁用.
这是我的代码:
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",int arg1) { // This should not be static // createTrivia(); trivia(); } }); // Return to Last Saved CheckPoint alertBox.setNegativeButton("Run Away!",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); } }
行:Button button =((AlertDialog)alertBox).getButton(AlertDialog.BUTTON_NEUTRAL);
给出错误:无法从AlertDialog.Builder转换为
AlertDialog
我该如何解决??我究竟做错了什么?
解决方法
您不能在AlertDialog.Builder上调用getButton().创建后必须在结果AlertDialog上调用它.换一种说法
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); }
构建器只是使构建对话框更容易的类,它不是实际的对话框本身.
HTH