ViewPager2 with fragments lazy inflation

from the CommonsWare Community archives

At June 17, 2019, 9:59am, rd7773 asked:

Usually, we use viewStubs in the fragments to lazily inflate complex views when using with view pager using the fragment’s setUserVisibleHint() method which is called by the PagerAdapter when fragment is going to be visible to user.

Now comes viewPager2, that needs a recyclerview adapter or viewPager2.FragmentStateAdapter if holders are fragments.
How to lazily inflate the fragments in this viewpager2 ? More specifically, is it possible to use viewStubs in for viewHolders and only inflate them from bindViewHolder ?

At June 17, 2019, 1:39pm, mmurphy replied:

I am unconvinced that setUserVisibleHint() is reliable in this context.

I have no idea. I have not used ViewPager2, and I don’t lazily inflate layouts.

I have no idea.

I am sorry that I cannot be of greater assistance on this topic!

At February 17, 2020, 4:39pm, jsmyth886 replied:

Considering ViewPager2 is now based off RecyclerView, is there any need to lazily inflate your fragment?

The RecyclerView, and now ViewPager2, will handle recycling of views as they come into view and scroll off the screen, thus keeping memory usage down automatically.

At February 17, 2020, 5:08pm, mmurphy replied:

I have not used ViewPager2, so I do not have any specific advice for it.

Also, I am uncertain what “lazily inflate your fragment” would mean in this context. With ViewPager, generally you would create the fragment when the adapter asked for it.