ViewPager2.setOffscreenPageLimit问题

问题描述

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

问题是... 只是为了测试ViewPager2。我将ViewPager2与TabLayout和附加的Fragments一起使用。然后,我将“屏幕外页面限制值”设置为1。我希望保持3页。 (当前页面,左页面,右页面),但是大约保留了6页。当我使用以前的ViewPager时,效果很好。

我做到了... 我在

代码是...

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();
    }
}

解决方法

我有同样的问题。我在使用 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);
}