Last Updated:

ViewPager on Android With Example

In this tutorial, we'll deal with the widget while writing a simple app. We'll look at the basic settings of the PagerAdapter adapter (needed for viewPager to work) and implement 3 widget screens. ViewPager

ViewPager Overview

The widget allows the user to swipe (swipe a finger across the screen from one side to the other) on pages with some data. Sam uses the View components and populates them with some passed data. In terms of interoperability, this is comparable to the ListAdapter and ListView adapter.ViewPagerViewPagerPagerAdapter

Example of creating a ViewPager in Android

Let's get down to practice and set the layout activity_main.xml layout of the ViewPager widget from the support library:

If you have extra indentations in RelativeLayout that were automatically generated by Android Studio, then just delete them.

Now let's create layouts for the widget screens. Here's the first mock-up of the view_screen_1.xml:ViewPager

Great, now we can start creating a model class that will store references to resources in a convenient form for us:

Attention! If you're not familiar with the Enum data type, be sure to read about it here.

Now let's move on to the most interesting thing – the adapter for our:ViewPager

  • The constructor takes as a parameter a context to initialize a class variable that is used to access and create View components from that data.SimplePagerAdapter(Context context)
  • The method uses an enumeration that corresponds to a specific position. Gets the data from it and returns the generated View component. This object is then used by the .instantiateItem(ViewGroup viewGroup, int position)isViewFromObject
  • The method removes a specific View from the ViewGroup.destroyItem()
  • The method simply returns the number of Views that are used in the ViewPager.getCount()
  • The method checks whether a particular object matches this position. As described just above, the second parameter is of type Object and is obtained from the .isViewFromObject()instantiateItem()
  • The method returns the text for the title of each screen. In our implementation, we didn't pass it to an ActionBar.getPageTitle()

We've created all the layouts and configured the adapter to display correctly, now let's initialize our ready-made SimplePagerAdapter adapter in the class method:ViewPageronCreate()MainActivity

Now it remains to run our simple example of creating a ViewPager in Android:

As you can see, we have 3 screens that can be scrolled through with a simple swipe.

You can download the ViewPager project on Android here.