Fragment life cycle

To create a Fragment, you must create a subclass of Fragment (or its existing subclass). The code for the Fragment class looks a lot like an Activity. It contains activity-like callback methods such as onCreate(), onStart(), onPause(), and onStop(). In fact, if you want to convert an existing Android application to use Fragments, you can move the code from the Activity's callback method to the Fragment's corresponding callback method. The Fragment life cycle that you know at least is as follows (the picture comes from the official android documentation)

illustrate flow chart
onAttach(Activity) called once the fragment is associated with its activity.
onCreate(Bundle) Fragment's initialization creation
onCreateView(LayoutInflater, ViewGroup, Bundle) Creates and returns
the view hierarchy associated with Fragment
onActivityCreated(Bundle) tells Fragment which Activity it is in has successfully created
onStart() makes the Fragment visible to the user (based on its containing Activity is starting)
onResume() makes the fragment start interacting with the user (based on its containing Activity is resuming)
onPause() the fragment no longer interacts with the user because its The Activity is being paused or
the Fragment action is modifying the Activity it is in.
onStop(): The Fragment is no longer visible to the user, either because its Activity is being stopped
, or the Fragment operation is modifying the Activity it is in.
onDestroyView(): Fragment cleans up resources related to its View.
onDestroy() finally cleans up all the state of the fragment
onDetach(): The fragment disassociates from the Activity it is in
Description of this picture


onViewStateRestored(Bundle) tells the Fragment that all saved view hierarchy state has been restored.

In fact, there are two methods that are often called in the Fragment life cycle, onViewStateRestored() and onSaveInstanceState(), which collect Fragment data and can retrieve stored data respectively. The effect of onViewStateRestored is the same as that of Activity's onRestoreInstanceState(). Fragment All saved view hierarchy state has been restored. And onSaveInstanceState() corresponds to the Activity's onSaveInstanceState() method, which means to save its current dynamic state so that it can be rebuilt later when a new instance of its process is restarted. The onSaveInstanceState() method may be called at any time before onDestroy(), so a more complete life cycle is often as follows:

For the state stored by onSaveInstanceState(Bundle), if a new instance of the fragment needs to be created later, the data placed in the Bundle will be provided to onCreate(Bundle), onCreateView(LayoutInflater, ViewGroup, Bundle), onActivityCreated(Bundle), onViewStateRestored( Bundle savedInstanceState) is available in the Bundle, it should be noted that savedInstanceState may be empty.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686732&siteId=291194637