How To Use ViewPager in Android

You need to create an Android activity that contains multiple pages, that can be flipped horizontally to show various content. The pages have a similar structure, only the content is different.

Here is how you do

1. Create a resource for the page template, here is how the current one looks like

  2. <ScrollView xmlns:android=""
  3. android:id="@+id/content"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent" >
  7. <LinearLayout
  8. android:orientation="vertical"
  9. android:layout_width="fill_parent"
  10. android:layout_height="fill_parent">
  12. <TextView
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:textAppearance="?android:attr/textAppearanceLarge"
  16. android:text="Large Text"
  17. android:id="@+id/title" />
  19. <TextView
  20. android:layout_width="fill_parent"
  21. android:layout_height="wrap_content"
  22. android:text="New Text"
  23. android:id="@+id/ct" />
  24. </LinearLayout>
  25. </ScrollView>

So we got a scroll view for everything and the fragment contains a title and the content

2. Create a class that inherits the Fragment and make sure it makes use of the layout created above. Make it so that it will be able to accept the values for the fields to be passed to the fields that are defined in the layout. The fields are passed at onCreate, so you cannot instantiate those fields from the class constructor, you have to store the values in some specifically created class fields and then onCreate transfers those values to the actual fields after they are created.

3. Create the current activity containing a ViewPager entry as follows. The main activity must extend FragmentActivity

  2. <?xml version="1.0" encoding="utf-8"?>
  3. <!-- activity_screen_slide.xml -->
  4. <
  5. xmlns:android=""
  6. android:id="@+id/pager"
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent" />

4. Create a class that extends FragmentStatePagerAdapter. Two methods are important, one is getCount that returns the number of pages and getItem that gets a zero based index and returns the page at that index - the page is of the fragment type we discussed above. Each page - a separate fragment.

5. Then in the main activity, get the instance of ViewPager (findViewById), create an instance of the adapter as defined above and pass it to the view pager instance. BTW, the adapter requires a FragmentManager as a parameter in the constructor. There is a method in the FragmentActivity that is called getSupportFragmentManager and that one returns the fragment manager needed. You don't touch it, just pass it to the adapter who uses it.

There is a tutorial on the Android developer site that pretty much outlines the steps above except it is much more verbose that is the reason I wrote the above.

Below is the project, if you are interested