Member-only story
A New Way to Handle Back Press in Fragments
Using the new ’OnBackPressedDispatcher’ in Android fragments
If you’ve been an Android developer for a while, the chances are you’ve handled back-press events using the onBackPressed
function in activities. That was fine until the introduction of architectural components and a single source of truth patterns.
In this modern Android development era, developers adapt to single-activity patterns, and the rest of the screens are implemented using fragments. This approach brings many advantages — one that I especially appreciate is that every outsource interaction should be done through that particular activity.
With such high-quality development ideas, developers tend to move from traditional activities to effective fragments. This puts many developers in a tricky position (myself included in some cases) regarding the usage of back press in fragments.
Problem
Transforming the development from activities to fragments brings with it some disadvantages due to the lack of features under the fragments library. Previously, if you wanted to implement the screens using fragments, when you wanted to handle back press, you didn’t have a native solution.
How It Works
One of the popular old school solutions from developers around the globe is through interfaces. The usage of this solution goes way back to 2014. Let me explain, though, in case you’re not familiar with it. First, create an interface with a single function, as shown below:
Then, we need to implement this interface on every fragment and return a boolean value: True
if the fragment observes the back-press event and false
if not. Have a look: