为什么 ViewPager2 延迟加载页面?

Why is ViewPager2 delaying to load pages?

我决定尝试 ViewPager2 的新稳定版本。

我的 ViewPager2 有很多页面,我正在使用 TabLayout 为每个页面(片段)提供可滚动的标签标题,但我在加载 ViewPager2 在我看来还是第一次。

这是正常行为吗?

ViewPager 上有一个 whole set of improvements

  • RTL (right-to-left) layout support
  • Vertical orientation support
  • Reliable Fragment support (including handling changes to the underlying Fragment collection)
  • Dataset change animations (including DiffUtil support)

ViewPager 中永远不会修复这些功能,因此迁移到 ViewPager2 将是获得这些功能的唯一途径。

我弄清楚了导致 ViewPager2 初始加载页面延迟的原因。

碰巧我使用了 com.google.android.material.tabs.TabLayout 中的 TabLayout 以及 ViewPager2 来为每个页面提供可滚动的标签标题。但是如果你有很多页面,我就是这样,UI 需要时间来设置每个选项卡并放置在 UI.

解决方法是去掉ViewPager2中的TabLayout,如果需要显示标题,通过更改和设置使用ToolBar作为每个页面的标题页指示符ToolBar 文字根据您的需要。

从好的方面来看,您最终会得到更干净的 UI,通过在屏幕中添加更多 space 供 ViewPager2 向用户显示其内容。

我注意到的另一件事是,如果您想充分利用 ViewPager2 性能优势,请使用默认的 viewpager 的 offscreenPageLimit,如下所述:

public void setOffscreenPageLimit (int limit)

Set the number of pages that should be retained to either side of the currently visible page(s). Pages beyond this limit will be recreated from the adapter when needed. Set this to OFFSCREEN_PAGE_LIMIT_DEFAULT to use RecyclerView's caching strategy. The given value must either be larger than 0, or #OFFSCREEN_PAGE_LIMIT_DEFAULT.

Pages within limit pages away from the current page are created and added to the view hierarchy, even though they are not visible on the screen. Pages outside this limit will be removed from the view hierarchy, but the ViewHolders will be recycled as usual by RecyclerView.

This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.

You should keep this limit low, especially if your pages have complex layouts. By default it is set to OFFSCREEN_PAGE_LIMIT_DEFAULT.

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

话虽如此,我强烈建议在所有情况下将您的 ViewPager 替换为 ViewPager2,因为 ViewPager 不再获得 Google 支持,并且 ViewPager2 除了我在这里所说的以外,还有很多东西可以提供:

RTL (right-to-left) layout support

Vertical orientation support

Reliable Fragment support (including handling changes to the underlying Fragment collection)

Dataset change animations (including DiffUtil support)

https://developer.android.com/jetpack/androidx/releases/viewpager2