Saturday, July 23, 2011

ViewPager example from PAUG

During a recent session at the Paris Android User Group (hi PAUG!) we did a live coding of a ViewPager example, it took around 5 minutes. What is a ViewPager? It is a tasty new class smothered in awesome sauce on a bed of rocking adapters, seriously I think I may use at least one in every Android app I make from now on. It was released as part of the updated Compatibility Package.

White on green was a great choice, right? very.... visible.

If you search for 'android view pager' you'll see many questions on how to implement smooth, finger tracking, horizontal view paging in Android, so it seems appropriate the solution is called ViewPager. ViewPager was launched at the end of last week as part of the updated Compatibility package and supports Android 1.6+.

Some of you may have been aware of the Workspace example open sourced with the I/O Sched app. An important difference between ViewPager and Workspace is that ViewPager pulls its views from an adapter, so like with a ListView as the items are slid off the screen they can be recycled and/or brought back in on the right side of the screen. The sample code for ViewPager shows this being done with a FragmentPagerAdapter, where each view is a fragment, giving you an amazing amount of control over your application.

In this example we are just sliding TextViews on and off the screen, here is the complete guide:

1) Download the update from Android SDK & AVD manager: Available Packages -> Android Repository -> Android Compatibility Package, revision 3. It will be installed in \extras\android\compatibility\v4

2) Create a new Android Project (I'm using Eclipse) and include the library. Properties -> Java Build Path -> Libraries -> Add External JARs -> android-support-v4.jar, it is in the install directory.
Update: As Thomas says if you're using the latest ADT you can now just right-click on your project -> Android Tools -> Add Compatibility Library

3) Your should now be able to use ViewPager in your Activity

4) If you use ViewPager in an xml layout, be sure to use the full reference, e.g.


5) Create a PagerAdapter to serve up your Views to the ViewPager. The key methods to implement are getCount(), instantiateItem(), destroyItem() and isViewFromObject() here are my implementations along with some JavaDoc from the source.

Note: It is up to the developer to add the views they are creating in instantiateItem() to the collection being passed in. The converse applies to destroyItem(), you must remove the item from the collection. The collection in this example is the ViewPager that is using the PagerAdapter.

The complete project source is at

A more professional and complete example can be found in the Compatibility Package samples (in the install directory), where a FragmentPagerAdapter implementation is provided. Using fragments inside a ViewPager can provide much better structure to an application as each view has its own FragmentActivity.