Android: onBackPressed() for Fragments

The problem

Daniel Wilson
2 min readSep 5, 2015

This is pretty basic Java but actually quite essential for any fragment-heavy application. My apps stick to one or two activities and everything else is kept neatly in fragments which are replaced as required. I find this leads to less code complexity but more extensibility for me, but your mileage and all that... I have a standard container layout in xml, and call the following to the swap fragments in it:

Of course by adding it to the back stack it pops when we press back by default, which is just lovely.

What if I had another container within the same layout as our R.id.content_container frame layout, but added in the same way? Let’s call it R.id.side_bar_container, which we add content to right after the above code. If I hit the back button in that case, it would be nice if it popped both fragments at the same time right? Equally it would be nice if either fragment could perform some extra code when the user hits back, and not just have the hosting activity know that we pressed back. He should share that info to anyone that would like to know!

Solution

To tell fragments when the back button has been pressed, first of all you need a base fragment which all of your other fragments inherit from. This base fragment implements the following:

Now in your hosting Activity, call any implementations of the interface before any fragments are popped:

That’s it! Any fragments which implement our onBackPressed() can do so and will be told as soon as the Activity is. So in my example, to pop both fragments at the same time I just have an extra pop in the side bar (which was added last):

Problems or suggestions? You know what to do :)

--

--