Search code examples
androidandroid-activityandroid-fragmentsandroid-dialogfragment

How do I hook into the back-pressed event when using a DialogFragment?


I want to know when the user presses the back button while my app is displaying a DialogFragment. Activity.onBackPressed() is only called if there is no DialogFragment. When the DialogFragment is open, pressing back closes the dialog but doesn't call onBackPressed(). I need to hook into this event because I need to close the dialog AND the Activity.

Hooking into DialogFragment.onDismiss() isn't good enough because it's called no matter how the dialog is dismissed. I only want to close the Activity when the user presses back.

Thanks in advance...


Solution

  • You could attach a key listener to the Dialog that your DialogFragment uses to display its content. To do get access to the Dialog, override onCreateDialog in your DialogFragment:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
      Dialog dialog = super.onCreateDialog(savedInstanceState);
      dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
          if (keyCode == KeyEvent.KEYCODE_BACK) {
            new Handler().post(new Runnable() {
              @Override
              public void run() {
                getActivity().finish();
              }
            });
          }
          return false;
        }
      });
      return dialog;
    }
    

    I'm not sure you need to wrap the call to finish inside the Runnable. It just seems a bit risky to finish the activity before the dialog has a chance to be dismissed. By posting the Runnable, you are allowing the key to be processed normally, letting Android close the dialog, and then after that your posted Runnable will run to finish the activity too.