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.
Lifecycle Methods of Fragment
|The first method to be call when the fragment is attached to the activity. This method executes once during the whole implementation.
|This method is called when a fragment is created. You have to initialize essential components and variables in this callback method.
|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.
|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
|This method is called when all the saved state of fragment view hierarchy has been restored.
|The fragment visible on the user’s device.
|This method is called to make the visible fragment interactive.
|This method is called when fragment is no longer interactive.
|The fragment is no longer visible.
|This method is called to ask the fragment to save its dynamic state.
|Cleanup all kind of resources and as well as view hierarchy.
|Final clean up of fragment’s state and its lifecycle.
|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.
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.