81

I have a dialogfragment for a floating dialog which includes a special keyboard that pops up when a user presses inside an EditText field (the normal IME is stopped from being displayed).

I would like the keyboard to be dismissed (visibility = GONE) when the user presses the back button (just as with a normal IME service) but the dialog to remain visible. However, there does not appear to be a way to do this as far as I can see from my fairly extensive reading on SO and elsewhere.

If I set the dialog to be non-cancelable then I don't get notified by onCancel() or onDismiss() because the dialog isn't cancelable.

If I set the dialog to be cancelable then I get notified, but the dialog is dismissed.

I can't attach an onKeyListener to the dialog in the fragment because it is replaced by the system so that the fragment can handle the dialog's life cycle.

Is there any way to do this? Or has access to the detection of key events been entirely fenced off for the purposes of the Fragment system?

user3227652
  • 811
  • 1
  • 6
  • 4

9 Answers9

183

The best way and cleanest way is to override onBackPressed() in the dialog you created in onCreateDialog().

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new Dialog(getActivity(), getTheme()){
        @Override
        public void onBackPressed() {
            //do your stuff
        }
    };
}
Ian Wong
  • 1,831
  • 1
  • 8
  • 3
  • 9
    The only solution I found that actually works properly. – Yoann Hercouet Sep 29 '14 at 11:02
  • 7
    This does not work in DialogFragments though since there is no onBackPressed() in the DialogFragment class. – Glen Pierce Nov 18 '15 at 01:00
  • 10
    DialogFragments wrap a Dialog - onCreateDialog creates this dialog. It works in DialogFragments. – Tom Apr 01 '16 at 00:04
  • I may only confirm this as best and most easy solution. Thanks for sharing this @Ian Wong – Menion Asamm Jun 14 '16 at 13:10
  • 1
    Definitely should be an accepted answer. Most native solution by far! – egorikem Apr 18 '17 at 12:01
  • `Dialog` could also be an instance of `AppCompatDialog` – SoftWyer Jun 26 '17 at 18:38
  • any ideas on what to do for `AppCompatDialogFragment` ? – Someone Somewhere Sep 21 '17 at 14:35
  • for some reason when you do it in BottomSheetDialogFragment the dialog becomes scuffed, the theme and styles are removed after this – Jenya Kirmiza Dec 17 '19 at 19:41
  • when doing this for a BottomSheetDialogFragment you can just create a new BottomSheetDialog(context, theme) and pass in the context and theme. If you check the super method that is all it does. – LeHaine Jun 04 '20 at 13:16
  • How do you this, when creating the dialog with `onCreateView` instead of `onCreateDialog`? I went with **Manimaran A**s solution for now. https://stackoverflow.com/a/53828416/5263365 – xian Sep 09 '20 at 20:21
  • For Kotlin: override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return object : Dialog(activity!!, theme) { override fun onBackPressed() { //do your stuff } } } – Tushar Pandey May 02 '21 at 20:08
80

I had the same problem than you and I've fixed it attaching the onKeyListener to the dialogfragment.

In the method onResume() of the class that extend of DialogFragment put these piece of code:

    getDialog().setOnKeyListener(new OnKeyListener()
    {
        @Override
        public boolean onKey(android.content.DialogInterface dialog, int keyCode,android.view.KeyEvent event) {

            if ((keyCode ==  android.view.KeyEvent.KEYCODE_BACK))
                {
                     //Hide your keyboard here!!!
                     return true; // pretend we've processed it
                }
            else 
                return false; // pass on to be processed as normal
        }
    });

Here one of the problems that you can find is this code is going to be executed twice: one when the user press tha back button and another one when he leave to press it. In that case, you have to filter by event:

@Override
public void onResume() {
    super.onResume();

    getDialog().setOnKeyListener(new OnKeyListener()
    {
        @Override
        public boolean onKey(android.content.DialogInterface dialog, int keyCode,
                android.view.KeyEvent event) {

            if ((keyCode ==  android.view.KeyEvent.KEYCODE_BACK))
            {
                //This is the filter
                if (event.getAction()!=KeyEvent.ACTION_DOWN)
                        return true;
                else
                {
                    //Hide your keyboard here!!!!!!
                    return true; // pretend we've processed it
                }
            } 
            else 
                return false; // pass on to be processed as normal
        }
    });
}
Iharob Al Asimi
  • 51,091
  • 5
  • 53
  • 91
Juan Pedro Martinez
  • 1,764
  • 1
  • 14
  • 24
25

As an addendum to Juan Pedro Martinez's answer I thought it would be helpful to clarify a specific question (one that I had) when looking at this thread.

If you wish to create a new DialogFragment and have it so the user can only cancel it using the back-button, which eliminates random screen touches from canceling the fragment prematurely, then this is the code that you would use.

In what ever code that you call the DialogFragment you need to set the cancelable setting to false so that NOTHING dismisses the fragment, no stray screen touches, etc.

DialogFragment mDialog= new MyDialogFragment();
mDialog.setCancelable(false);
mDialog.show(getFragmentManager(), "dialog");

Then, within your DialogFragment, in this case MyDaialogFragment.java, you add the onResume override code to have the dialog listen for the Back Button. When it's pressed it will execute the dismiss() to close the fragment.

@Override
 public void onResume() 
 {
     super.onResume();

     getDialog().setOnKeyListener(new OnKeyListener()
     {
         @Override
         public boolean onKey(android.content.DialogInterface dialog, 
                              int keyCode,android.view.KeyEvent event) 
         {
              if ((keyCode ==  android.view.KeyEvent.KEYCODE_BACK))
              {
                   // To dismiss the fragment when the back-button is pressed.
                   dismiss();
                   return true;
              }
              // Otherwise, do nothing else
              else return false;
         }
   });

Now your dialog will be called with the "setCancelable" to false, meaning nothing (no outside clicks) can cancel it and shut it down, and allowing (from within the dialog itself) only the back button to close it.

Ganbatte!

Brandon
  • 1,300
  • 1
  • 15
  • 24
  • 1
    Perfect, thanks, I wanted to prevent accidental outside clicks whilst maintaining back button functionality, for me all I had to do was setCancelable(false) on the dialog instance in onCreateView inside the DialogFragment. – Meanman Aug 10 '16 at 10:15
  • 1
    Thanks, This answer suits best to my condition. – Araju Jan 09 '20 at 07:41
19

How has no one suggested this?

public Dialog onCreateDialog(Bundle savedInstanceState) {
  Dialog dialog = super.onCreateDialog(savedInstanceState);

  // Add back button listener
  dialog.setOnKeyListener(new Dialog.OnKeyListener() {
    @Override
    public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
      // getAction to make sure this doesn't double fire
      if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_UP) {
        // Your code here
        return true; // Capture onKey
      }
      return false; // Don't capture
    }
  });

  return dialog;
}
Andrew James
  • 191
  • 1
  • 3
15

Use Fragment onCancel override method. It's called when you press back. here is a sample:

@Override
public void onCancel(DialogInterface dialog) {
    super.onCancel(dialog);

    // Add you codition
}
javadroid
  • 1,355
  • 1
  • 15
  • 39
Manimaran A
  • 167
  • 1
  • 3
  • 3
    Note, that with this approach you cannot handle whether the DialogFragment will be dismissed or not. You can just get notified that it is to be dismissed – Leo Droidcoder Jul 24 '19 at 18:56
  • Indeed @Leo Droidcoder Any idea how to intercept back button pressed before the dialogfragment cannot be dismissed ? – matdev Mar 18 '20 at 14:41
5

When creating the dialog, override both onBackPressed and onTouchEvent :

        final Dialog dialog = new Dialog(activity) {
            @Override
            public boolean onTouchEvent(final MotionEvent event) {
                //note: all touch events that occur here are outside the dialog, yet their type is just touching-down
                boolean shouldAvoidDismissing = ... ;
                if (shouldAvoidDismissing) 
                    return true;
                return super.onTouchEvent(event);
            }

            @Override
            public void onBackPressed() {
                boolean shouldAvoidDismissing = ... ;
                if (!shouldSwitchToInviteMode)
                    dismiss();
                else
                    ...
            }
        };
android developer
  • 106,412
  • 122
  • 641
  • 1,128
2

Prevent canceling DialogFragment:

dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.setOnKeyListener { dialog, keyCode, event ->
    keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP
}
Benny
  • 1,392
  • 1
  • 15
  • 23
1

Use onDismiss() callback of DialogFragment with a closeActivity flag

private var closeActivity: Boolean = true    

override fun onDismiss(dialog: DialogInterface?) {
        super.onDismiss(dialog)

        if (closeActivity) {
            activity!!.finish()
        }
    }
Vasudev
  • 1,318
  • 12
  • 14
-1

AndroidX OnBackPressedDispatcher can also be option for someone

KaMyLL
  • 841
  • 1
  • 7
  • 12