Listening to Fragments… from the outside
Most Android developers out there dealt at least once in their career with
Application.ActivityLifecycleCallbacks, but did you know the same thing can be done with
The reasons why
Let’s take a step back. Usually, you don’t need to be aware of the lifecycle of a
Fragment from outside: for example, you might need to listen to multiple
Fragment instances without changing the code for each of them.
Imagine you are working on an SDK, and you need to react to each
Fragment being created. You could ask your users to register each of their classes, or you could create a base class that has to be extended, but it’s not always possible. Let’s put ourselves in this situation for the following paragraphs.
How does it work?
There are a lot of similarities between the
FragmentLifecycleCallbacks and its
Activity counterpart, leaving the specific lifecycle events aside. The first one is that, even if both of them are in fact declared as
abstract classes, the former comes with default no-op implementations, while the latter does not.
Certainly, this has everything to do with the number of events that can be sent in each case. Another difference is that the
FragmentLifecycleCallbacks have to be attached to the
ActivityLifecycleCallbaks are usually attached to the
Application. This is, of course, a logical difference, as both of them are bound to the component that will start the
Fragment or the
As we mentioned in the previous paragraph,
FragmentLifecycleCallbacks offer a wide range of callbacks that cover the whole lifecycle of a
Fragment, but you can just override the methods you need in your case.
In the example, we are only interested in a few functions, just to test out the functionality:
Now that we created the main entry point for listening, we need to attach the object to the
FragmentManager: we can do it with an API call that accepts 2 parameters. The first one is the listener, while the second one is a
recursive. When the latter is set to
true, the same listener is attached to each
childFragmentManager, so that every
Fragment in the hierarchy can trigger the events. The listener can be attached pretty easily, with just one line of code:
While this API can be unfamiliar to most, there might be a case in your career when you need to listen to
Fragment instances and their lifecycle, and these functions come in handy.
If you want to play around with this feature, you can find it in a playground project on Github.