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

后端 未结 18 1979
无人及你
无人及你 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:40

    Here's something if you are using DialogFragment - which is the recommended way to handle Dialogs anyway.

    What happens with AlertDialog's setButton() method (and I imagine the same with AlertDialogBuilder's setPositiveButton() and setNegativeButton()) is that the button you set (e.g. AlertDialog.BUTTON_POSITIVE) with it will actually trigger TWO different OnClickListener objects when pressed.

    The first being DialogInterface.OnClickListener, which is a parameter to setButton(), setPositiveButton(), and setNegativeButton().

    The other is View.OnClickListener, which will be set to automatically dismiss your AlertDialog when any of its button is pressed - and is set by AlertDialog itself.

    What you can do is to use setButton() with null as the DialogInterface.OnClickListener, to create the button, and then call your custom action method inside View.OnClickListener. For example,

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        AlertDialog alertDialog = new AlertDialog(getActivity());
        // set more items...
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", null);
    
        return alertDialog;
    }
    

    Then, you may override the default AlertDialog's buttons' View.OnClickListener (which would otherwise dismiss the dialog) in the DialogFragment's onResume() method:

    @Override
    public void onResume()
    {
        super.onResume();
        AlertDialog alertDialog = (AlertDialog) getDialog();
        Button okButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        okButton.setOnClickListener(new View.OnClickListener() { 
            @Override
            public void onClick(View v)
            {
                performOkButtonAction();
            }
        });
    }
    
    private void performOkButtonAction() {
        // Do your stuff here
    }
    

    You will need to set this in the onResume() method because getButton() will return null until after the dialog has been shown!

    This should cause your custom action method to only be called once, and the dialog won't be dismissed by default.

提交回复
热议问题