Wednesday, October 19, 2011

Simple ViewPager for Android

You would have seen many applications recently, which make use of the new and awesome ViewPager that allows views to be horizontally scrollable. The new Android Market app also implements a flavor of the ViewPager, although it's a little more complex that what we will see here. This class is not available directly for you to use. Check this blog for some insight. It would required you to download a compatibility library from Google, add it to your project wherever you would like to use it, and go about paging views.

And yes, it's very simple to implement. I have coded up a little sample where it shows you how to use a ViewPager with a simple PagerAdapter. More or less, it works like the ListViews. Although there is not much documentation for this, it's quite easy to set up everything.

Firstly, you would need to add the ViewPager into your layout file.

Listing of main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" android:layout_width="fill_parent"
    <TextView android:text="Page 1" android:id="@+id/textViewHeader"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center" android:padding="10dip" android:textStyle="bold"></TextView>
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/viewPager" />
In this sample, we are using an extra TextView which would show the current page you are on.

Setting up the ViewPager
ViewPager viewPager = (ViewPager) findViewById(;
MyPagerAdapter adapter = new MyPagerAdapter(this);
This code is almost identical to what we would do for a ListView or Gallery. The only difference is that the adapter here, extends a PagerAdapter instead.

The PagerAdapter

The PagerAdapter has a few methods that you would implement. For this example, I have four different views, one for each page. 2 are ListViews, a TextView and a Button, not in that order. Here are the methods that you would need to implement. Look at the MyPageAdapter class for more.

public void destroyItem(View view, int arg1, Object object) {
         ((ViewPager) view).removeView((View)object);
public int getCount() {
          return views.size();
public Object instantiateItem(View view, int position) {
           View view = views.get(position);
           ((ViewPager) view).addView(view);
           return view;
public boolean isViewFromObject(View view, Object object) {
           return view == object;
 And you are done!!! Sweet.... You can find the whole source code here.