Question

I'm trying to change my ViewPager transition animation. I'd like to have the same behavior as the default gallery, when you switch from one photo to the next one. It's basically an animation where the current page goes to the left while the next one comes from behind it and grows larger.

I've seen that I can change the animation with a PageTransformer.

pager.setPageTransformer(false, new PageTransformer() {

        @Override
        public void transformPage(View page, float position) {
            if (position < 0) {

            } else {
                final float normalizedposition = Math.abs(Math.abs(position) - 1);
                page.setScaleX(normalizedposition / 2 + 0.5f);
                page.setScaleY(normalizedposition / 2 + 0.5f);
            }
        }
    });

With that, I have the current page sliding to the left, that's ok. The new page starts small in size and grows, that's also ok. But, the page comes from the right to center. I'd like to remove the translation and have it already in the middle, but small, hidden by the current page.

If I add page.setTranslationX(1080 * (-(position))); then the next pages stays in the middle of the screen, but they are visible at all time above the current page. If I also add alpha to the page, the page appearing isn't hidden behind the old one.

I've tried to check in the source code of the gallery app but I didn't found any reference to the transformPage function.

Was it helpful?

Solution

Turns out to be easy. It is in the demos in the android developper website.

public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.75f;

public void transformPage(View view, float position) {
    int pageWidth = view.getWidth();

    if (position < -1) { // [-Infinity,-1)
        // This page is way off-screen to the left.
        view.setAlpha(0);

    } else if (position <= 0) { // [-1,0]
        // Use the default slide transition when moving to the left page
        view.setAlpha(1);
        view.setTranslationX(0);
        view.setScaleX(1);
        view.setScaleY(1);

    } else if (position <= 1) { // (0,1]
        // Fade the page out.
        view.setAlpha(1 - position);

        // Counteract the default slide transition
        view.setTranslationX(pageWidth * -position);

        // Scale the page down (between MIN_SCALE and 1)
        float scaleFactor = MIN_SCALE
                + (1 - MIN_SCALE) * (1 - Math.abs(position));
        view.setScaleX(scaleFactor);
        view.setScaleY(scaleFactor);

    } else { // (1,+Infinity]
        // This page is way off-screen to the right.
        view.setAlpha(0);
    }
}
}

See here (Depth page transformer).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top