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)
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

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 onStart and 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 onResume method.

Be careful to manage the timing of the respective execution sequences so that you avoid race conditions.

Scenario 2: Activity with Fragment is rotated

Scenario 2: Activity with Fragment is rotated

State management

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 onCreate, onCreateView and onActivityCreated.

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 onActivityCreated.

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.