如何禁用MaterialAlertDialogBu​​ilder中的按钮

时间:2020-05-17 00:46:48

标签: disable material-dialog

如何禁用MaterialAlertDialogBu​​ilder中的按钮? 我想做类似此屏幕截图的功能: enter image description here

我编写了以下代码(对话框包含EditText,用户应在其中输入自己喜欢的食物名称)。

final MaterialAlertDialogBuilder dialogEnterDishName = new MaterialAlertDialogBuilder(context);
        //...
        final EditText editTextEnterDishName = new EditText(context);
        dialogEnterDishName.setView(editTextEnterDishName);

        dialogEnterDishName.setPositiveButton(getString(R.string.dialog_enter_dish_name_positive_button), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!editTextEnterDishName.getText().toString().equals(""))
                    //...
                else {
                    //TODO Make posititve button disabled until the user enters any character
                }
            }
        });
        //...
        dialogEnterDishName.show();
    }

我已经知道,AlertDialog类(MaterialAlertDialogBu​​ilder扩展了AlertDialog.Builder)具有方法public Button getButton(int whichButton),但是我不能在MaterialAlertDialogBu​​ilder中使用它。

请帮助!

1 个答案:

答案 0 :(得分:0)

确保在为AlertDialog(通过.show()调用)充气后调用getButton()函数。如果您要进行其他操作,则没有按钮可以获取。

为了启用后退按钮,您可以使用TextWatcher。此处有更多详细信息:Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged

val customLayout = LayoutInflater.from(context).inflate(R.layout.your_alert_dialog, null, false)
val dialog = MaterialAlertDialogBuilder(context)
            .setTitle("Provide name")
            .setView(customLayout)
            .setNeutralButton("Cancel") { dialog, _ -> dialog.dismiss() }
            .setPositiveButton("Confirm") { _, _ -> }
            .create()
        
dialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
相关问题