为什么在ViewPager2中使用notifyDataSetChanged会破坏PagerTransformer?

8

我正在使用版本为1.0.0-beta05的ViewPager2,搭配RecyclerView.Adapter和ZoomOutPageTransformer。当我们调用notifyDataSetChanged时,ViewPager的视图会崩溃。

在版本1.0.0-alpha01中,他们说notifyDataSetChanged已经完全正常运行(解决了VP1的缺陷)。

崩溃视图

正常行为

        pagerAdapter?.clickListener = this
        with(pager) {
            clipToPadding = false
            clipChildren = false
            offscreenPageLimit = 3
        }
        pager.adapter = pagerAdapter
        pager.setPageTransformer(ZoomOutPageTransformer())


        GlobalScope.launch(Dispatchers.Main) {
            // launch a new coroutine in background and continue
            repeat(15) {
                delay(5000L) // non-blocking delay for 1 second (default time unit is ms)
                Log.e("hello", "notify")
                pagerAdapter?.notifyDataSetChanged()
            }
        }

我没有改变数据源,只是做了这个小测试,问题仍然存在,在每次调用notifyDataSetChanged后,视图会随机地被重置为丑陋的大小。


请分享您的ZoomOutPageTransformer类的代码,同时查看此链接 https://dev59.com/olMH5IYBdhLWcg3w1TuK#58056129 - AskNilesh
我在文档https://developer.android.com/training/animation/screen-slide-2#zoom-out中使用了相同的类。问题是当调用notifyDataSetChanged时,视图会被放置在任何地方。 - user12221228
你有检查过这个解决方案吗?https://dev59.com/olMH5IYBdhLWcg3w1TuK#58056129 - AskNilesh
我测试了这个解决方案,同样的问题出现了。 - user12221228
2个回答

7

你找到任何解决方案了吗?

对我来说,我需要调用ViewPager2requestTransform()函数。但是我需要在适配器notifyDataSetChanged()之后进行post函数调用。

...
adapter.notifyDataSetChanged()
vb.viewpager.post {
    // I am using Fragment, and I get some crashes while I am switching tabs/fragments,
    // so here I reference the `nullable` _vb property
    _vb?.viewpager?.requestTransformation()
}

希望这对你有帮助。

1

你应该阅读 API 文档:

 /**
 * Sets a {@link PageTransformer} that will be called for each attached page whenever the
 * scroll position is changed. This allows the application to apply custom property
 * transformations to each page, overriding the default sliding behavior.
 * <p>
 * Note: setting a {@link PageTransformer} disables data-set change animations to prevent
 * conflicts between the two animation systems. Setting a {@code null} transformer will restore
 * data-set change animations.
 * ...
 */
public void setPageTransformer(@Nullable PageTransformer transformer) {}

尝试重置页面转换器来修复它:
pager.setPageTransformer(null)
adapter.notifyDataSetChanged()
pager.setPageTransformer(myPageTransformer)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接