How to prevent a dialog from closing when a button is clicked

后端 未结 18 2225
无人及你
无人及你 2020-11-21 23:59

I have a dialog with EditText for input. When I click the \"yes\" button on dialog, it will validate the input and then close the dialog. However, if the input

18条回答
  •  我在风中等你
    2020-11-22 00:26

    Inspired by Tom's answer, I believe the idea here is:

    • Set the onClickListener during the creation of the dialog to null
    • Then set a onClickListener after the dialog is shown.

    You can override the onShowListener like Tom. Alternatively, you can

    1. get the button after calling AlertDialog's show()
    2. set the buttons' onClickListener as follows (slightly more readable I think).

    Code:

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // ...
    final AlertDialog dialog = builder.create();
    dialog.show();
    // now you can override the default onClickListener
    Button b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i(TAG, "ok button is clicked");
            handleClick(dialog);
        }
    });
    

提交回复
热议问题