Tutorial

Android ViewPager Example Tutorial

Published on August 3, 2022
author

By Anupam Chugh

Android ViewPager Example Tutorial

ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we’ll implement a ViewPager that swipes through three views with different images and texts.

Android ViewPager

Android ViewPager widget is found in the support library and it allows the user to swipe left or right to see an entirely new screen. Today we’re implementing a ViewPager by using Views and PagerAdapter. Though we can implement the same using Fragments too, but we’ll discuss that in a later tutorial. The ViewPager uses a PagerAdapter whose job is to supply views to the MainActivity similar to what a ListAdapter does for a ListView.

Android ViewPager Example

android viewpager, viewpager in android, viewpager, android viewpager example tutorial

Android ViewPager Example Code

The activity_main.xml consists solely of the ViewPager as shown below. activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

The MainActivity.java is given below. MainActivity.java

package com.journaldev.viewpager;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new CustomPagerAdapter(this));
    }
}

The role of the MainActivity in the above code is to just reference the ViewPager and set the CustomPagerAdapter that extends the PagerAdapter. Before we discuss the CustomPagerAdapter class, let’s look into the ModelObject class. ModelObject.java

package com.journaldev.viewpager;

public enum ModelObject {

    RED(R.string.red, R.layout.view_red),
    BLUE(R.string.blue, R.layout.view_blue),
    GREEN(R.string.green, R.layout.view_green);

    private int mTitleResId;
    private int mLayoutResId;

    ModelObject(int titleResId, int layoutResId) {
        mTitleResId = titleResId;
        mLayoutResId = layoutResId;
    }

    public int getTitleResId() {
        return mTitleResId;
    }

    public int getLayoutResId() {
        return mLayoutResId;
    }

}

The enum above lists all the pages of the ViewPagers. There are three pages with their respective layouts. The layout of a single page is given below. view_blue.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="@android:color/holo_blue_dark"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second View"
        android:layout_gravity="center_horizontal"
        android:textSize="28sp"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Swipe left to\nFirst View"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:minLines="2"
        android:id="@+id/textView2"
        android:padding="@dimen/activity_horizontal_margin"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Swipe right to\nThird View"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:padding="@dimen/activity_horizontal_margin"
        android:minLines="2"
        android:id="@+id/textView3"
        android:layout_alignTop="@+id/textView2"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

The remaining two pages have similar layouts and are given in the source code of this project. CustomPagerAdapter.java

package com.journaldev.viewpager;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class CustomPagerAdapter extends PagerAdapter {

    private Context mContext;

    public CustomPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        ModelObject modelObject = ModelObject.values()[position];
        LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
        collection.addView(layout);
        return layout;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getCount() {
        return ModelObject.values().length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        ModelObject customPagerEnum = ModelObject.values()[position];
        return mContext.getString(customPagerEnum.getTitleResId());
    }

}
  1. CustomPagerAdapter(Context context) : The constructor needs a Context reference. The context is saved as a member variable of the class since it’s used later to access the individual page layouts from the enum class
  2. instantiateItem : In this case, we use the enum and inflate the particular enum value’s associated layout. Then, we add the newly inflated layout to the ViewGroup(collection of Views) maintained by the PagerAdapter, and then we return that layout. The object being returned by this method is also used later on, as the second parameter in the isViewFromObject method
  3. destroyItem : This method removes a particular view from the ViewGroup maintained by the PagerAdapter
  4. getCount : It simply returns the number of views that will be maintained by the ViewPager. For this example, the count is the number of enum values in the model object
  5. isViewFromObject : This method checks whether a particular object belongs to a given position, which is made simple. As noted earlier, the second parameter is of type Object and is the same as the return value from the instantiateItem method
  6. getPageTitle : At a given position, we need to supply the PagerAdapter with a title. This usually manifests itself in the ActionBar as the Activity’s title, or sometimes tabs will hook into this method for labelling each tab. In this case we’ve kept it for labelling only

The image below shows the app in action. android viewpager example, android ViewPager, ViewPager in android This brings an end to ViewPager in android example tutorial. You can download the Android ViewPager Project from the below link.

Download Android ViewPager Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 17, 2016

plz provide me the tutorial related to android animation … whole relative layout should be scrolled up when the button is click. and the button should also be present in same relative layout…

- Diwas poudel

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 2, 2016

    How do i add activity to each fragment in the view pager?

    - Dennis

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 16, 2017

    You can add a fragment to an Activity. Doesn’t work the other way, Dennis!

    - Anupam Chugh

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 5, 2018

      import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager pager = (ViewPager) findViewById(R.id.viewPager); pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager())); } private class MyPagerAdapter extends FragmentPagerAdapter { public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int pos) { switch(pos) { case 0: return FirstFragment.newInstance(“FirstFragment, Instance 1”); case 1: return SecondFragment.newInstance(“SecondFragment, Instance 1”); case 2: return ThirdFragment.newInstance(“ThirdFragment, Instance 1”); case 3: return ThirdFragment.newInstance(“ThirdFragment, Instance 2”); case 4: return ThirdFragment.newInstance(“ThirdFragment, Instance 3”); default: return ThirdFragment.newInstance(“ThirdFragment, Default”); } } @Override public int getCount() { return 5; } } }

      - piyush kumar

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 18, 2016

        Thank you! Really nice! Look at this library - https://github.com/Cleveroad/SlidingTutorial-Android

        - Richard

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 1, 2016

          Very helpful. But how i add more views(more than three). Please help me. I am a novice in android development.

          - Ras

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 1, 2016

          I got it. Thanks for your article.

          - Ras

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          April 7, 2017

          how?

          - Zaur

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 10, 2016

            thanks …

            - atefeh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 21, 2016

              Nice article…If i want to perform operations on each view like clickOnListener on Button where should i write the java code for it.I am novice for Android development .Please help me out

              - Surendra Bharathi

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                October 24, 2016

                THANK YOU SO MUCH!!! I tried a bunch of other tutorials but to no avail. I tried this one and it worked like a charm! Keep up the great work!

                - Tim

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 16, 2017

                Glad to hear that Tim. If you want me to cover any topics feel free to comment below!

                - Anupam Chugh

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  March 27, 2017

                  hello, how can I reverse the order of view_red, view_green and view_blue? in your examples when I launch the application I see first the view_red. but if I want see the second view (middle_view) so that I can swipe right or swipe left how can I do this? thank you very much

                  - paolo

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    April 10, 2017

                    Really Helpful Thanks

                    - Joginder Pal Verma

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      June 22, 2017

                      How to use OnItemClickListener with viewpager and get position of clicked item and displays the clicked item???

                      - Niks

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        September 6, 2017

                        how to get data from sqlite to display in android viewpager

                        - Santosh

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        September 6, 2017

                        please give me reply

                        - Santosh

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          October 5, 2018

                          public class MainActivity extends AppCompatActivity { float x1,x2; float y1, y2; int currentPage; ViewPager mViewPager; String ID; List listID = new ArrayList(); List listName = new ArrayList(); List listMtrno = new ArrayList(); String SearchString = null; CursorPagerAdapter mAdapter; Cursor cursor; DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); getSupportActionBar().setDisplayShowHomeEnabled(true); databaseHelper = new DatabaseHelper(this); setContentView(R.layout.pager); databaseHelper = new DatabaseHelper(MainActivity.this); cursor = databaseHelper.fetch(); mAdapter = new CursorPagerAdapter(this, cursor); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mAdapter); mViewPager.setPageTransformer(true, new ZoomOutPageTransformer()); if (extras != null) { SearchString = extras.getString(“SearchFlag”); if (SearchString != null) { mViewPager.setCurrentItem(Integer.parseInt(SearchString) - 1); } else { if (cursor.moveToFirst()){ while(!cursor.isAfterLast()){ cursor.moveToNext(); } } } Log.d(“MainActivity”, “Search(A): " + SearchString); } } private class CursorPagerAdapter extends PagerAdapter { private Cursor cursor; private LayoutInflater inflater; public CursorPagerAdapter(Context context, Cursor cursor) { Log.d(“Main Activity”, “MyCursorPagerAdapter.onCreate()”); this.cursor = cursor; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void swapCursor(Cursor cursor) { //if(cursor != null) { Log.d(“Main Activity”, “swapCursor().”); this.cursor = cursor; //notifyDataSetChanged(); //} } @Override public int getCount() { if(cursor == null) { return 0; } else { return cursor.getCount(); } } @Override public void destroyItem(ViewGroup view, int position, Object object) { cursor.moveToPosition(position); (view).removeView((LinearLayout) object); } @Override public Object instantiateItem(ViewGroup view, int position) { position = position % cursor.getCount(); cursor.moveToPosition(position); LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_listener, null); TextView f1_recno = layout.findViewById(R.id.TV_recno); TextView f1_acctno = layout.findViewById(R.id.TV_acctno); TextView f1_route = layout.findViewById(R.id.TV_route); TextView fl_name = layout.findViewById(R.id.TV_name); TextView fl_mtrno = layout.findViewById(R.id.TV_mtrno); f1_recno.setText((cursor.getPosition() + 1) + " of " + cursor.getCount() + " records”); f1_acctno.setText(cursor.getString(cursor.getColumnIndex(“ACCTNO”))); f1_route.setText(cursor.getString(cursor.getColumnIndex(“ROUTE”))); fl_name.setText(cursor.getString(cursor.getColumnIndex(“NAME”))); fl_mtrno.setText(cursor.getString(cursor.getColumnIndex(“MTRNO”))); (view).addView(layout); return layout; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; }

                          - piyush kumar

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            October 10, 2017

                            hi thank you this is great but i have question where can i set edittext ?

                            - farzad

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 14, 2018

                              Thanks for the tutorial. 2 questions: 1) Can this logic be used for Wear? 2) Could the second view contain a button which changes the background of view 1 (for example)? Best regards

                              - Stefan Meyer

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 15, 2018

                              Yes. For both. For the second: Refer this tutorial: Android Passing Data Between Fragments

                              - Anupam Chugh

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                September 30, 2018

                                RED(R.string.red, R.layout.view_red), BLUE(R.string.blue, R.layout.view_blue), GREEN(R.string.green, R.layout.view_green); sir i get the R error … its not resolved … its not sloved by rebuild

                                - dipesh

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                October 10, 2018

                                I am also facing this Problem

                                - Umer Lilla

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  March 14, 2019

                                  Its great information. I want to know that if i want to swipe layout just like you mention in your article, I also add the actionbar/tool and have 4 menu item. It is possible i can also swipe same layout with my menu item which are showing at action bar on top. if yes then what code also entered above article and where. Thanks

                                  - Umair

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    September 15, 2019

                                    how to change my bg color to swipe my card view in my fragments

                                    - chavda

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    January 27, 2020

                                    u can use backgroundTint then given ur clr then it change

                                    - divya

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      September 23, 2019

                                      Thank you man, useful sharing…

                                      - Oguzhan

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        June 1, 2020

                                        great explanation … my question is how to set curlview in view pager?

                                        - wajeeha

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          August 6, 2020

                                          Well this defied everything I thought I knew about these adapters. I have some questions… Why not take the context from the ViewGroup collection? LayoutInflater inflater = LayoutInflater.from(collection.getContext()); Also pardon my ignorance but, I have taken a good solid few hours to try to analyze the code behind the ViewPager and I’ve failed to found even a hint of how this instatntiateItem method works, everything in that code is too disjointed… inheritance after inheritance is a headache. I’m amazed how the devs chose to use the ViewGroup pointers with that collection.addView(layout); method, even tho I personally prefer to do those kinds of things even when not needed, I thought that that was just a bad design decision on my part, but seen it here was a surprise, maybe there is so much asynchronism(?) happening back there they actually need this?? but wouldn’t that make a mismatch between the view added via collection.addView() and the one returned by the instantiateItem?? In theory one could do a mini recycler view inside the instantiate item method by checking if the view at current position is or not null/same as new one (RIGHT!!!), and I tried the whole day yesterday to do this but I failed miserably. After trying to go my own way without success for hours, I did it your way and it works perfectly, so thanks!!

                                          - Juan Andrade

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            October 1, 2020

                                            Hi I want write a adapter for use in fragments and sliding image is it possible? Like abase adapter for use sliding images and fragments . Can you please helpe me?

                                            - rezayi

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              February 8, 2021

                                              Hi there, thank you for this tutorial. I just have a question how can I assign variables in each activity, for example, let’s say I have an ImageView in the view_blue layout which I want when is clicked does something.

                                              - John

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                October 10, 2021

                                                I am making an android book app with java using web view and my pages in html. As I am new to this, I am trying to find out how to slide from one html page to another instead of clicking buttons. please if you know how , set an example because like I said I am new to this. here is a link to the app I made if you want to have a look(its very small for testing purposes, with 3 pages). https://github.com/Philip2021-Gr/book-app-sliding-between-html-files So far no one gave me any reliable answer that refers to a rookie like me in coding nor i find a video tutorial that saws how to do that with html pages that are stored in your assets folder. I hope some one sees this tread and try to help me cause I am struggling for weeks now with this problem.

                                                - Philp

                                                  Join the Tech Talk
                                                  Success! Thank you! Please check your email for further details.

                                                  Please complete your information!

                                                  Become a contributor for community

                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                  DigitalOcean Documentation

                                                  Full documentation for every DigitalOcean product.

                                                  Resources for startups and SMBs

                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                  Get our newsletter

                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                  The developer cloud

                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                  Get started for free

                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                  *This promotional offer applies to new accounts only.