gpt4 book ai didi

java - 如何禁用 AlertDialog 中的按钮?

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:47 24 4
gpt4 key购买 nike

我正在尝试编写一个带有 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",
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);

}
}

行:

Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);

给出错误:

Cannot cast from AlertDialog.Builder to 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

关于java - 如何禁用 AlertDialog 中的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7392321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com