0

如何禁用 MaterialAlertDialogBu​​ilder 中的按钮?我想在此屏幕截图中制作类似的功能: 在此处输入图像描述

我编写了以下代码(对话框包含 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 extends AlertDialog.Builder)有一个方法 public Button getButton(int whichButton),但我不能在 MaterialAlertDialogBu​​ilder 中使用它。

请帮忙!

4

1 回答 1

2

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

为了启用按钮返回,您可以使用 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
于 2020-09-28T14:11:48.827 回答