Better Programming

Advice for programmers.

Follow publication

Member-only story

A New Way to Handle Back Press in Fragments

Siva Ganesh Kantamani
Better Programming
Published in
3 min readOct 12, 2020

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:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (3)

Write a response