ViewPager in android example

             ViewPager is a Layout manager that allows the user to flip left and right like the pages of a book. It is commonly used in screens like setup wizard or slideshow. The layout is supplied an implementation of a PagerAdapter to generate the pages that the view shows.
     PagerAdapter much like a ListView. The main difference is here list items are inflated while pages are inflated in the latter. There are mainly two ways in which the layouts of ViewPager can be defined:

ViewPager in Android
1.  Each page is a fragment : For this, the ViewPager implements a FragmentStatePagerAdapter (used when there is large number of pages) or FragmentPagerAdapter (used when the number of pages are less).
2. Each page is a copy of a layout : i.e. a layout defined in an xml file is reused. Just the values are changed based on the page number.

Android lets only 3 pages to be created at a time, one currently visible to the user, one on its left and one on its right. Other pages are destroyed and their layouts are re-used. Any animation and dynamic content should be implemented keeping in mind this limitations.

ViewPager also animates the change of page. There are default animations but custom animations can always be added. The custom animation class must be a child of PageTransformer.

Let’s get hands on the implementation of ViewPager:

We will be building an application with three pages. Each page will be made of a fragment.

Creating a Custom Adapter:

public class CustomAdapter extends FragmentPagerAdapter {
    public CustomAdapter(FragmentManager fm) {

    public Fragment getItem(int position) {
        //set for which position which fragment is to be inflated
        switch (position) {
            case 0:
                return new FragmentOne();
            case 1:
                return new FragmentTwo();
            case 2:
                return new FragmentThree();
        return null;

    public int getCount() {
        //there are three fragments to be displayed in the viewPager
        return 3;

     This adapter extends FragmentPagerAdapter because we have just three pages. Mainly two functions needs to be overridden i.e. getItem(int position) that returns a Fragment and getCount() that returns the number of pages will be displayed in the ViewPager. We have defined a constructor as well. This can be used to pass values like number of pages, titles for pages, etc. It is not necessary as even if you do not define a constructor, by default an empty constructor is assigned. FragmentOne, FragmentTwo and FragmentThree are three fragments defined to be used as pages in our ViewPager.

Now, let’s see how this adapter is put to use in the main activity.

public class MainActivity extends AppCompatActivity {

    RelativeLayout relativeLayout;
    ViewPager viewPager;
    CustomAdapter customAdapter;

    protected void onCreate(Bundle savedInstanceState) {

        viewPager = (ViewPager) findViewById(;
        relativeLayout = (RelativeLayout) findViewById(;
        //defining an object of CustomAdapter
        customAdapter = new CustomAdapter(getSupportFragmentManager());


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

        android:layout_height="match_parent" />

It is as simple as you are seeing here. We just have a tag in the XML layout and just wrapped the custom adapter we created earlier to the ViewPager.

Now we will be designing a simple slideshow of photos. This will illustrate another way of using ViewPager. Here no fragments are required. A simple xml layout is created and that will be reused with some values changed dynamically depending on the page number.

Let’s get started with creating a custom adapter:

public class CustomAdapter extends PagerAdapter {
    Context mContext;
    LayoutInflater mLayoutInflater;
    int[] imageIds;
    String[] photoTitle;
    ImageView imageView;
    TextView text;

    public CustomAdapter(Context context, int[] imageIds, String[] photoTitle) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.photoTitle = photoTitle;

    public Object instantiateItem(ViewGroup container, final int position) {
        View itemView = mLayoutInflater.inflate(R.layout.layout_photo, container, false);

        imageView = (ImageView) itemView.findViewById(;
        text = (TextView) itemView.findViewById(;

        return itemView;

    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);

    public int getCount() {
        //there are three fragments to be displayed in the viewPager
        return imageIds.length;

    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((RelativeLayout) object);

Atleast three functions have to be overridden. getCount() has the same function as explained earlier, to return the number of pages in the ViewPager. instantiateItem () as the name suggests, creates new items i.e. pages. Hence, here the xml layout is inflated and all the views in the layout are initialised. destroyItem() is used to destroy the item once created and no more in use.   IsViewFromObject() is used to return the type of object the xml layout is. Like here the parent layout used is RelativeLayout. Hence, a RelativeLayout object is returned.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""




This is a simple layout followed by each page. It has an ImageView and a TextView. The MainActivity class remains the same as before.

So, we learned two type of implementations of ViewPager. If you have queries please comment below.

Alternative link to Project

Hope this tutorial clearly explains how to use ViewPager in Android with example..



Post a Comment