Android Fragment life cycle

Fragment life cycle is similar to Activity

Fragment must depend on Activity to run, so Activity life cycle calls take precedence over Fragment, and Fragment is much lighter than Activity.

  1. onAttach: Called when the Fragment is associated with the Activity to obtain the value passed by the Activity
  2. onCreate: Called before the view is created
  3. onCreateView: Called when creating a Fragment view
  4. onActivityCreated: Called after the view is created
  5. onStart: Called when the interface view is displayed
  6. onResume: Called when the interface view has focus
  7. onDestroyView: Called when the Fragment view is removed
  8. onDestroy : Called when destroyed
  9. onDetach: Called when the Fragment is no longer attached to the Activity

Fragment startup process

Called when Fragment is created:
onAttach—>onCreate—>onCreateView—>onActivityCreated—>onStart—>onResume

Called when Fragment is invisible:
onPause --> onStop

Called when Fragment is destroyed:
onPause—>onStop—>onDestroyView—>onDestory—>onDetach

flow chart

insert image description here

During the development process, you need to pay attention to the methods that may be commonly used

setUserVisibleHint() This method is called before onCreateView, so this method cannot operate the view. Otherwise return a null pointer error

Usage scenario : When used with ViewPager, there is an internal pre-cache mechanism (by default, one page is cached in advance) , and lazy loading can be done through this method. Because of the mechanism of ViewPager, the front and rear Fragments are loaded during the initialization process. Before the user manually triggers the second page, the latter Fragment is loaded and the network request is made to render data, which completely violates the lazy loading mechanism. Therefore, this method needs to be used. When the Fragment is visible, the network request is made and the data rendering refresh interface is implemented.

Note : When ViewPager is not used, but the Fragment is added hide show through FragmentTransaction, the setUserVisibleHint() method is not called. The reason is that Fragment does not go through any life cycle when the hide() and show() methods are called .

   @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
    
    
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
    
    
            //界面可见
        } else {
    
    
            //界面不可见
        }
    }

When onHiddenChanged() uses FragmentTransaction to control the hide and show of the fragment, then this method will be called. Whenever you use hide or show on a Fragment, the Fragment will automatically call this method.
(Usage situation: you manage Fragment yourself, not when you manage it with viewpager)

Guess you like

Origin blog.csdn.net/u013290250/article/details/103991926