In many cases, the fragment lifecycle upper limit should be lower than FragmentManager/Activity. For example, ViewPager off-screen interfaces should not be resumed

Ideally, this can be done through the following API

supportFragmentManager.beginTransaction()
      .setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
      .commit()
Copy the code

Setting the maximum Lifecycle to kill.state.resumed will effectively remove the restriction (because that is the highest Lifecycle State)

This will allow the setUserVisibleHint() API to be discarded

SetMaxLifecycle begins and ends

How should this function be implemented? Let’s follow the commit log to clarify the official thinking

Move part of the logic of BackStackRecord to the parent FragmentTransaction class

Add the setMaxLifecycle API to FragmentTransaction

Save the fragments maxState

Deprecated setUserVisibleHint

The FragmentPagerAdapter constructor adds an argument that uses the setMaxLifecycle() API to ensure that the fragment is visible to the user

Deprecated FragmentStatePagerAdapter original single constructor, it is recommended to use the new structure

As theViewPager2 1.0.0Official release, withViewPagerThe interaction ofFragmentPagerAdapterFragmentStatePagerAdapterHas been deprecated

So far we le shun the emergence of the setMaxLifecycle setUserVisibleHint deprecated and ViewPager related FragmentPagerAdapter and FragmentStatePagerAdapter deprecated

SetMaxLifecycle internal logic

Now how does setMaxLifecycle work

FragmentStateManager class is added to manage the fragment state. The FragmentStateManager class is used to manage the fragment state

Then add the method computeMaxState() to the class to calculate the maximum fragment lifecycle.

This method was later renamed computeExpectedState() and the moveToExpectedState() method was added

The computeExpectedState() method calculates the life cycle the fragment should be in based on the Fragment mMaxState

The Fragment’s mMaxState is set through the FragmentManager’s setMaxLifecycle() method, which is called when BackStackRecord executes the OP, The OP value is set through setMaxLifecycle() of FragmentTransaction

At this point we have clarified the internal logic of setMaxLifecycle()

conclusion

We can see that the setMaxLifecycle() method has been introduced in order to make the fragment lifecycle correct, and the FragmentStateManager has been abstracted to better manage the fragment state. With less code and less responsibility, the fragment’s internal logic becomes clearer and clearer

  • For how to migrate to ViewPager2, go to the official video

  • For the new API lazy loading implementation, please go to the new implementation of lazy loading on Androidx

About me

I am Flywith24, and my blog content has been classified here. You can click Watch in the upper right corner to get updates of my articles in time, oh 😉

  • The Denver nuggets
  • Jane’s book
  • Github