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

时间:2012-04-25 22:00:06

标签: 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();

1 个答案:

答案 0 :(得分: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);

如果你想让按钮看不见,那就更难了。我现在无法测试是否在按钮上调用setVisibility()会产生好结果......

HTH