1

I have a PageTransformer that correctly displays my ViewPager with the second element correctly scaled, but there is no alpha applied to the second element. However, upon dragging the ViewPager a miniscule amount, the next view is properly displayed. The code for both my alpha and scale is identical, I'm not sure what the issue here is.

I have tried calling code from a handler once the ViewPagerAdapter has things added to it (such as viewPager.scrollBy() and pager.beginFakeDrag()) but these didn't help.

viewPager.setOffscreenPageLimit(2) is set. I have tried setting alpha to the views programmatically when instantiated in the Adapter but it has no effect. If the scale is correctly being applied then the alpha should be as well, surely.

@Override
    public void transformPage(View page, float position)
    {
        float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
        float alphaFactor = Math.max(MIN_ALPHA, 1 - Math.abs(position));

        page.setScaleX(scaleFactor);
        page.setScaleY(scaleFactor);

        page.setAlpha(alphaFactor);
    }
Josh Laird
  • 6,974
  • 7
  • 38
  • 69

2 Answers2

1

(EDIT) CORRECT SOLUTION:

Replace ViewPager with ViewPager2.

Useful resources:

LAZY (AND NOT SO COOL, ERROR PRONE) SOLUTION:

Unfortunately for me, I did not have the property android:animateLayoutChanges=true set in my layout.

I faced the same problem when I moved the ViewPager from an Activity to a Fragment.

I think the problem is due to the fact I reused the fragment. Upon a FragmentTransaction, the ViewPager technically still has its old value, so its view doesn't need to change, that's why the PageTransformer isn't fired.

Basically, all you need to do is to set the ViewPager's currentItem to 0, and then set it to the value you want to.

This is my snippet (MyViewPager.kt, but you don't need to override ViewPager).

init {
    post {
        currentItem = 0
    }
}


fun setCurrentPage(position: Int) {
    post {
        setCurrentItem(position, true) // I want smooth scroll
    }
}   
0

I had android:animateLayoutChanges=true set on the ViewPager. Once I removed this, it loaded correctly. Don't ask me why it was there in the first place.

Josh Laird
  • 6,974
  • 7
  • 38
  • 69