Whether it’s providing custom navigation or performing an analytics operation, sometimes you want your app to respond to a user back press in a customized manner.
One way to achieve this is by using the Activity
’s onBackPressed()
method.
Called when the activity has detected the user’s press of the back key. The OnBackPressedDispatcher will be given a chance to handle the back button before the default behavior of Activity.onBackPressed() is invoked.
Activities and Fragments
This can be implemented pretty easily in an Activity
or Fragment
like so:
DialogFragment
What about DialogFragments
? You may realize that the same approach we used in Fragment
s does not work.
Turns out, unlike the above two examples, you will need to override the Dialog
’s onBackPressed()
that gets created in onCreateDialog()
:
That’s it! Now you can insert your custom back press logic to be executed whenever the back press is invoked.