The Android Lifecycle cheat sheet — part III : Fragments
In this series:
* Part I: Activities — single activity lifecycle
* Part II: Multiple activities — navigation and back stack
* Part III: Fragments — activity and fragment lifecycle (this post)
* Part IV: ViewModels, Translucent Activities and Launch Modes
The diagrams are also available as a cheat sheet in PDF format for quick reference.
In this section we’ll cover the behavior of a fragment that is attached to an activity. Don’t confuse this scenario with that of a fragment added to the back stack (see Tasks and Back Stack for more information on fragment transactions and the back stack).
Scenario 1: Activity with Fragment starts and finishes
Note that it’s guaranteed that the Activity’s
onCreate is executed before the Fragment’s. However, callbacks shown side by side — such as
onResume — are executed in parallel and can therefore be called in either order. For example, the system might execute the Activity’s
onStart method before the Fragment’s
onStart method, but then execute the Fragment’s
onResume method before the Activity’s
Be careful to manage the timing of the respective execution sequences so that you avoid race conditions.
Scenario 2: Activity with Fragment is rotated
Fragment state is saved and restored in very similar fashion to activity state. The difference is that there’s no
onRestoreInstanceState in fragments, but the Bundle is available in the fragment’s
Fragments can be retained, which means that the same instance is used on configuration change. As the next scenario shows, this changes the diagram slightly.
Fragments — Scenario 3: Activity with retained Fragment is rotated
The fragment is not destroyed nor created after the rotation because the same fragment instance is used after the activity is recreated. The state bundle is still available in
Using retained fragments is not recommended unless they are used to store data across configuration changes (in a non-UI fragment). This is what the ViewModel class from the Architecture Components library uses internally, but with a simpler API.
If you find errors or you think something important is missing, please report them in the comments. Also, let us know what other scenarios you would like us to write about.