Decomposing FragmentLifecycleCallbacks
Hi! Today I’ll continue describing tools that for some reason don’t get much attention. My previous article was about the features of ActivityLifecycleCallbacks and how it can be used for purposes other than logging lifecycle. But apart from Activity there’s also Fragment, and I’d like to take a look at it too.
I got straight to the point: I opened search by class in AndroidStudio (Cmd/Ctrl + O) and entered FragmentLifecycleCallbacks. To my surprise, my search query returned FragmentManager.FragmentLifecycleCallbacks. The most impatient readers mentioned it in the comments, so here’s the next chapter of this story. Take a look under the cut!
What is it?
The interface is similar to ActivityLifecycleCallbacks but for Fragment.
Compared to ActivityLifecycleCallbacks, it’s controlled by FragmentManager instead of Fragment itself, which has a few advantages. For example, the methods of this interface have the Pre- prefix, and they are called before the corresponding Fragment. Methods without prefix are called before these Fragment methods are executed.
Besides that, FragmentLifecycleCallbacks is not an interface but an abstract class. I think it is designed to enable implementation by default for the methods.
Now let’s get to the interesting stuff: launching it.
Registration
To make FragmentLifecycleCallbacks work, you need to register it in FragmentManager. To do that, you need to call FragmentManager.regirterFragmentLifecycleCallback() and enter two parameters there: callback itself and the recursive flag. The flag indicates whether this callback should be applied only to this FragmentManager or if it should be forwarded recursively to all childFrangmentManagers of this Fragment, and further in the hierarchy.
FragmentLifecycleCallback must be registered before Activity.onCreate(), otherwise we might miss some events, for example, when restoring status.
It doesn’t look pretty, and in some cases it requires creating something like a basic Activity. However, if you’ve read my article on ActivityLifecycleCallbacks, then you know that basic Activity can be easily replaced =).
Now we get the real synergy of callback methods. Using this solution, we can reach almost any Activity and Fragment object created in the system. Now when we see the whole thing, we can make this system work for us.
Examples of use
Straight to dependency injection: yes, now you can spread dependencies over the whole app even if you have a Single Activity Application. Do you remember the example with RequireCoolTool from the previous article? The same can be done for any Activity and Fragment in the app. You’ve probably already guessed how, haven’t you? I’ll still give an example.
Of course, it perfectly works with Dagger too.
I think you’ll cope with other DI frameworks, but if you won’t, let’s discuss it in the comments.
Of course, you can do all the same things as with Activity, for example, send analytics.
What examples of use can you give?