Parallax Effect in Android's ViewPager

pdj picture pdj · Sep 14, 2012 · Viewed 18.6k times · Source

I'm trying to emulate a parallax effect when sliding through my fragments, I've read about beginFakeDrag and fakeDragBy but to be honest, I don't know even if it's the best approach to my problem.

Anyone has done something similar with the ViewPager or have a hint about how should I approach this?

Thank you

Answer

Chris Stillwell picture Chris Stillwell · Sep 16, 2016

An easy way to do this without using a custom library is to implement ViewPager.PageTransformer

I created my layouts to use the same id for their background element. For my example all background images will use the id background

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/background"
    android:src="@drawable/img12"
    android:scaleType="fitXY"/>

Then when I go in to implement ViewPager.PageTransformer I can reference that image like so:

public class Transformer implements ViewPager.PageTransformer{
    @Override
    public void transformPage(View page, float position) {
        if(position >= -1 && position <= 1){
            page.findViewById(R.id.background).setTranslationX(-position * page.getWidth() / 2);
        } else {
            page.setAlpha(1);
        }
    }
}

Finally, I assign my ViewPager.PageTransformer to my ViewPager like so.

ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setPageTransformer(false, new Transformer());