About Me

My photo
I'm a colonist who has declared war on machines and intend to conquer them some day. You'll often find me deep in the trenches fighting off bugs and ugly defects in code. When I'm not tappity-tapping at my WMD (also, known as keyboard), you'll find me chatting with friends, reading comics or playing a PC game.

Thursday, August 28, 2014

An InfiniteViewPager for Android

Hey folks!This time around I'm going to be writing a programming post related to my adventures in Android!

Le Problème:

A ViewPager in Android does not support carousel-like scrolling of its items. We can scroll from the first item to the last item but not directly from the last item back to the first item and vice-versa. See the image below to get an idea of what we'd like to achieve.

La Solution:

I've seen several versions of an InfiniteViewPager that present hackish solutions to this problem. Standing on the shoulders of giants, I decided to take a stab at this problem and have finally come up with a non-hackish way of doing things. The basic concept is to truly cycle the fragments in the ViewPager. The Android Studio project has been hosted on github at https://github.com/angelorohit/InfiniteViewPager. Go grab it! Have you got it? OK. What we need are the two JAVA files InfiniteViewPager and InfiniteViewPagerAdapter.

The InfiniteViewPager provides its own OnPageChangeListener. This listener performs circular rotation of the fragments in the ViewPager's adapter whenever a new page is selected. If the user has navigated to the last fragment in the ViewPager, then the first fragment is removed from its position in front and is placed at the back. Similarly, if the user has navigated to the first fragment in the ViewPager, the last fragment is removed from its position at the back and is placed in front.

The InfiniteViewPagerAdapter simply stores a List of Fragments for the InfiniteViewPager.


Since we are actually cycling between the fragments in the ViewPager, this can only work if there are 3 or more fragments in it. The code has been written such that if the ViewPager has less than 3 fragments in it, no circular cycling is performed, although the user can still swipe back and forth between the existing fragments in the ViewPager.

That's it! Hopefully, someone will find this InfiniteViewPager useful! Happy coding!