0

I am trying to migrate my app from the legacy ViewPager to ViewPage2. And I found that unlike ViewPager, ViewPager2 will not call fragment's onCreate() or onCreateView when the fragment is not visible.

For example, user is on Fragment[N], when using ViewPager, Fragment[N+1] will be created in background and I can do some preparation work there (e.g. start fetching data, decoding image etc.).

However, when I tried the ViewPager2 sample, I found that those fragment lifecycle callbacks only get called when Fragment[N+1] becomes visible to user. Otherwise, only the fragment's constructor(init method) is called in the background. But I need the initialized view objects for the preparation work. So, how to solve this problem? Or if I am doing things in a wrong way, please point out the correct direction.

Thanks a lot.

Robin
  • 10,052
  • 6
  • 31
  • 52

1 Answers1

1

You can possibly solve some of your problems by adjusting the OffscreenPageLimit

https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2#setOffscreenPageLimit(int)

This will change it to bring the Fragments +/- X number to Started state either side of the current one.

Only the current displayed Fragment is brought to Resumed State.

As Viewpager2 is just a recyclerview of Fragments it is optimised to try and be efficient and not create Fragments until they are really needed to be displayed.

Andrew
  • 8,198
  • 2
  • 15
  • 35
  • Thanks bro, this works like a charm. I remember legacy ViewPager also has this method and just forgot to use this on the new ViewPager2. – Robin Mar 24 '20 at 04:24