Why notifyDataSetChanged blow up PagerTransformer in ViewPager2?

1.7k Views Asked by At

I am using ViewPager2 version 1.0.0-beta05, with a RecyclerView.Adapter, and ZoomOutPageTransformer, I found that when we call notifyDataSetChanged, the ViewPager view blow up.

In Version 1.0.0-alpha01, they said that notifyDataSetChanged fully functional (VP1 bugs addressed)

Blowed view

Normal behavior

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

I didn't change the datasource, I just made this small test and the problem still persist, the view get been resized ugly randomly after each call of notifyDataSetChanged.

2

There are 2 best solutions below

0
On

You should to read the api doc:

 /**
 * 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) {}

To fix it try to reset Page Transformer:

pager.setPageTransformer(null)
adapter.notifyDataSetChanged()
pager.setPageTransformer(myPageTransformer)
0
On

did you find any solution?

For me, I have to call ViewPager2's requestTransform() function. But I need to post the function call after adatper.notifyDataSetChanged().

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

Hope this helps.