Lifecycle of Android Fragments


5th February, 2023

Android fragments have their own events, layouts and lifecycle. In this section we will discuss the various stages of fragments lifecycle.

Lifecycle of Android Fragments

A Fragment’s lifecycle begins when the fragment is attached to an Activity. The fragment lifecycle is shown below.

Fragment Lifecycle

Lifecycle Methods of Fragment

Method Description
onAttach() The first method to be call when the fragment is attached to the activity. This method executes once during the whole implementation.
onCreate() This method is called when a fragment is created. You have to initialize essential components and variables in this callback method.
onCreateView() The system calls this method to create User Interface of the fragment. This method returns view component but if the fragment doesn't have a UI, then you can return a null.
onViewCreated() This method is called immediately after onCreateView(). onViewCreated is a make sure that view is fully created and ensures that the fragment's root view is non-null
onViewStateRestored() This method is called when all the saved state of fragment view hierarchy has been restored.
onStart() The fragment visible on the user’s device.
onResume() This method is called to make the visible fragment interactive.
onPause() This method is called when fragment is no longer interactive.
onStop() The fragment is no longer visible.
onSaveInstanceState() This method is called to ask the fragment to save its dynamic state.
onDestroyView() Cleanup all kind of resources and as well as view hierarchy.
onDestroy() Final clean up of fragment’s state and its lifecycle.
onDetach() The fragment is no longer associated with the host Activity.

Fragment’s Lifecycle States, Callback methods and View’s Lifecycle

The Fragment (androidx.fragment:fragment) class implements the LifecycleOwner (androidx.lifecycle:lifecycle-common) interface. This interface expose the Lifecycle object. So we can get fragment states using getLifecycle() method .

The Lifecycle.State Enum provides the possible states of Lifecycle object.

Fragment Lifecycle states enum

The fragment’s view have their own separate lifecycle. It is managed independently from fragments’ lifecycle. The following image describes the lifecycle of Android Fragment that relates to the callback methods and view’s lifecycle.

Android Fragment Lifecycle

Happy coding!

Leave a Reply