'ViewPager2.setOffscreenPageLimit() problem

API 30 Android 10.0+(Google APIs), AVD (x86)

Problem is... Just to test for ViewPager2. I used ViewPager2 with TabLayout and attached Fragments. Then I set the 'off screen page limit value' by 1. I expected to be maintained 3 pages. (current, left, right page) But about 6 pages are maintained. When I use the previous ViewPager, It is work well.

I did... I read document at <Android Developers website>. But I can't find a reason for above problem and I don't know that 'OFFSCREEN_PAGE_LIMIT_DEFAULT ' in the document mean How many page to maintain. It is defined just -1.

Code is...

public class MainActivity extends AppCompatActivity { 
    private TabLayout tabLayout; 
    private ViewPager2 viewPager; 
    private ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);

        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(new ViewPagerAdapter(this, 9));

        new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText("Tab " + (position + 1));
            }
        }).attach();
    }
}


Solution 1:[1]

I have same problem. I resolved with follow code when used setOffscreenPageLimit(1):

/**
 * Sets whether the LayoutManager should be queried for views outside of
 * its viewport while the UI thread is idle between frames.
 *
 * <p>If enabled, the LayoutManager will be queried for items to inflate/bind in between
 * view system traversals on devices running API 21 or greater. Default value is true.</p>
 *
 * <p>On platforms API level 21 and higher, the UI thread is idle between passing a frame
 * to RenderThread and the starting up its next frame at the next VSync pulse. By
 * prefetching out of window views in this time period, delays from inflation and view
 * binding are much less likely to cause jank and stuttering during scrolls and flings.</p>
 *
 * <p>While prefetch is enabled, it will have the side effect of expanding the effective
 * size of the View cache to hold prefetched views.</p>
 *
 * @param enabled <code>True</code> if items should be prefetched in between traversals.
 *
 * @see #isItemPrefetchEnabled()
 */
RecyclerView.LayoutManager layoutManager =  ((RecyclerView)(viewPager.getChildAt(0))).getLayoutManager();
if(layoutManager != null) {
    layoutManager.setItemPrefetchEnabled(false);
}


/**
 * Set the number of offscreen views to retain before adding them to the potentially shared
 * {@link #getRecycledViewPool() recycled view pool}.
 *
 * <p>The offscreen view cache stays aware of changes in the attached adapter, allowing
 * a LayoutManager to reuse those views unmodified without needing to return to the adapter
 * to rebind them.</p>
 *
 * @param size Number of views to cache offscreen before returning them to the general
 *             recycled view pool
 */ 
RecyclerView recyclerView=  ((RecyclerView)(viewPager.getChildAt(0)));
if(recyclerView != null) {
    recyclerView.setItemViewCacheSize(0);
}

Solution 2:[2]

when yo create TabLayoutMediator set smoothScrool=false and view pager doesn´t create all fragments but another bug comes with this change. When you navigate making click in tabs sometimes viewpager doesn´t work fine and you can see two fragments in the screen, half and half

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sabrina N
Solution 2 Felipe Pereira Garcia