如何禁用警报对话框中的按钮?

我正在尝试用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);

给出错误:

无法从 AlertDialog.Builder 强制转换为 AlertDialog

如何解决此问题?


答案 1

您无法调用 .它必须在创建后调用结果。换句话说getButton()AlertDialog.BuilderAlertDialog

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);
}

构建器只是一个类,使构建对话框更容易...它不是实际的对话框本身。

呵呵


答案 2

在我看来更好的解决方案:

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);
                    }
                }
            }
        });

推荐