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

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

    The answer at this link is a simple solution, and which is compatible right back to API 3. It is very similiar to Tom Bollwitt's solution, but without using the less compatible OnShowListener.

    Yes, you can. You basically need to:

    1. Create the dialog with DialogBuilder
    2. show() the dialog
    3. Find the buttons in the dialog shown and override their onClickListener

    I made minor adaptions to Kamen's code since I was extending an EditTextPreference.

    @Override
    protected void showDialog(Bundle state) {
      super.showDialog(state);
    
      class mocl implements OnClickListener{
        private final AlertDialog dialog;
        public mocl(AlertDialog dialog) {
              this.dialog = dialog;
          }
        @Override
        public void onClick(View v) {
    
            //checks if EditText is empty, and if so tells the user via Toast
            //otherwise it closes dialog and calls the EditTextPreference's onClick
            //method to let it know that the button has been pressed
    
            if (!IntPreference.this.getEditText().getText().toString().equals("")){
            dialog.dismiss();
            IntPreference.this.onClick(dialog,DialogInterface.BUTTON_POSITIVE);
            }
            else {
                Toast t = Toast.makeText(getContext(), "Enter a number!", Toast.LENGTH_SHORT);
                t.show();
            }
    
        }
      }
    
      AlertDialog d = (AlertDialog) getDialog();
      Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);
      b.setOnClickListener(new mocl((d)));
    }
    

    Such fun!

提交回复
热议问题