Spice up your ViewPager (part2): change animation type.

In the first post of the series “Spice up your ViewPager”, I have described how to control the speed of the horizontal scroll in order to make smoother and cleaner transitions between pages. In this second post instead, I am going to show you how to further enhance your transitions with custom animations.

Let’s look again at the showcase app, and in particular to the second row of widgets.


By clicking on the Spinner (drop-down menu) you can change the animation of the ViewPager underneath. Go ahead and try a few different animation types. Notice how the ViewPager changes behaviour while you try to swipe among the pages. Try to modify also the scroll duration with the plus and minus buttons. This simple app will help you to understand better how the animation is executed and what is the best duration for each type of animation.


Let’s continue from the previous implementation of our CustomScrollerAll we need to do in order to change animation is to addan Interpolator argument to the constructor and then pass it to its parent Scroller as shown below.

public CustomScroller(Context context, Interpolator interpolator, int duration) {
    super(context, interpolator);
    mDuration = duration;

So now we can create a CustomScroller with the interpolator type that we prefer and then assign it to the ViewPager. For example let’s say that we want a ViewPager with a transition which lasts half second and which allows pages to slide-out quickly and to enter-in slowly. This is the code that we need to achieve the effect just described:

CustomScroller customScroller = new CustomScroller(this, new FastOutSlowInInterpolator, 500);
Field mScroller = ViewPager.class.getDeclaredField("mScroller");
mScroller.set(mPager, customScroller);

You can check all android default interpolators here. No need to say that you can achieve other kind of animations with a custom interpolator, but this is another topic which I am not going to cover in this post.

For now feel free to try the code used for the showcase app (GitHub repo), and let’s build something fancy starting from there!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s