如何在运行时禁用AlertDialog的正按钮?

Bin*_*abu 4 android android-widget

有没有办法在运行时禁用AlertDialog的正按钮,比如在TextWatcher中?

AlertDialog.Builder(this)
                    .setTitle(getString(R.string.createvfs))
                    .setView(newVSView_v11)
                    .setPositiveButton(getString(R.string.okay),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                }
                            })
                    .setNegativeButton(getString(R.string.cancel),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    // Canceled.
                                }
                            }).show();
Run Code Online (Sandbox Code Playgroud)

Dev*_*red 7

您需要获取对话框本身的引用以便稍后进行修改,因此您必须稍微更改构建器,但随后您可以随时调用AlertDialog.getButton()以启用或禁用该按钮.像这样......

//Use create() so you can get the instance back
AlertDialog dialog = AlertDialog.Builder(this)
                .setTitle(getString(R.string.createvfs))
                .setView(newVSView_v11)
                .setPositiveButton(getString(R.string.okay),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                            }
                        })
                .setNegativeButton(getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                // Canceled.
                            }
                        }).create();
//Then show it
dialog.show();

/* ...Sometime in the distance future... */
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
Run Code Online (Sandbox Code Playgroud)

如果你想让按钮看不见,那就更难了.我现在无法测试是否setVisibility()按下按钮会产生良好的效果......

HTH

  • 我想要禁用该按钮,我尝试了你的代码,但它是因为dialog.getButton(DialogInterface.BUTTON_POSITIVE)返回null.:S (4认同)