API 30 Android 10.0+(Google API)、AVD (x86)
问题是...
只是为了测试 ViewPager2。我将 ViewPager2 与 TabLayout 和附加片段一起使用。然后我将“离屏页面限制值”设置为 1。我预计将保留 3 页。 (当前、左、右页)但保留了大约6页。当我使用以前的ViewPager时,它工作得很好。
我做了...
我阅读了文档 Android 开发者网站>。但我找不到上述问题的原因,我不知道文档中的“OFFSCREEN_PAGE_LIMIT_DEFAULT”意味着要维护多少页。它被定义为-1。
代码是...
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)