OnBackPressedDispatcher Android

BackPress handling in Fragments

Satya Pavan Kantamani
3 min readJul 3, 2020
Photo by Christian Wiediger on Unsplash

History

If a user is navigating from one screen to the other on an application, the Android system will maintain a stack of screens that is generally referred to as a back stack. Back Navigation is nothing but how users navigate back through the stack of screens they visited previously. Android by default handles this back navigation. But in some cases, we might need to provide our own Back behavior in order to provide the best user experience.

From the introduction of fragments, it’s always been an interesting aspect of handling BackPress inside fragments itself. Mostly we followed the technique of creating an interface and implementing them in the fragments on the other hand inside the activity on back press listener we check the current fragment instance and call that interface method to get the work done. That was a boring thing that we are following since quite a long time

In this post let’s check both the new and old ways of how to handle the back press inside Fragments.

The old way to school

Step 1: Create an Interface that has a callback method to handle the back press.

--

--

Satya Pavan Kantamani

Android Dev, Interested in Traveling, App development. Based in Hyderabad, India. Catch me at https://about.me/satyapavankumar