0

How can I disable button in MaterialAlertDialogBuilder? I want to make similar functionality like in this screenshot: enter image description here

I wrote the following code (dialog contains EditText where user should input his favorite food name).

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

I already knew, that class AlertDialog (MaterialAlertDialogBuilder extends AlertDialog.Builder) have a method public Button getButton(int whichButton), but I can't use it in MaterialAlertDialogBuilder.

Please, help!

1 Answers1

2

Make sure that you are calling getButton() function after you inflate your AlertDialog (through .show() call). If you are doing it other way around there is no button to get.

In order to enable button back you can use TextWatcher. More details here: 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
kk.
  • 3,747
  • 12
  • 36
  • 67
coehorn
  • 21
  • 4