Fra*_*zzo 10 java android classcastexception android-alertdialog
我想AlertDialog
用3个按钮写一个.如果不满足某个条件,我希望禁用中间的中性按钮.
码
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这条线:
Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);
Run Code Online (Sandbox Code Playgroud)
给出错误:
无法从AlertDialog.Builder转换为AlertDialog
我该如何解决?
Dev*_*red 19
你不能打电话getButton()
给AlertDialog.Builder
.必须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);
}
Run Code Online (Sandbox Code Playgroud)
构建器只是一个类,使构建对话框更容易......它不是实际的对话框本身.
HTH
我认为更好的解决方案:
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);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
诀窍是您需要使用AlertDialog
按AlertDialog.Builder.show()
方法重新调整的对象。无需致电AlertDialog.Builder.create()
。
例:
AlertDialog dialog = alertbox.show();
if(monsterint > playerint) {
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
button.setEnabled(false);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12571 次 |
最近记录: |