Understanding Android ViewPager and Custom PagerAdapter

In this tutorial, we are going to go deeper in understanding android ViewPager and custom PagerAdapter.

Android ViewPager is a layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.

Note this class is currently under early design and development. The API will likely change in later updates of the compatibility library, requiring changes to the source code of apps when they are compiled against the newer version.

The PagerAdapter providing the adapter to populate pages inside of a ViewPager. You will most likely want to use a more specific implementation of this, such as FragmentPagerAdapter or FragmentStatePagerAdapter.

When you implement a PagerAdapter, you must override the following methods at minimum:

instantiateItem(ViewGroup, int)

destroyItem(ViewGroup, int, Object)

getCount()

isViewFromObject(View, Object)

With this in mind, we are going to write an android app that will display images with their names as we swipe through the image collections.

If you want to learn how to implement android horizontal carousel with HorizontalScrollView, I will suggest you first read my tutorial on this topic.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android viewpager

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidViewPager

Package: com.inducesmile.androidviewpager

Select Blank Activity

Name your activity : MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Strings.xml

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<string name="app_name">Android ViewPager</string>
<resources>
    <string name="app_name">Android ViewPager</string>
</resources>

Colors.xml

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
    <color name="colorDivider">#B6B6B6</color>
</resources>

activity_main.xml

We are going to add a ViewPager layout in the main layout file. Set the layout width and height to match_parent. Go to the layout folder inside the res folder, open the activity_main.xml and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidviewpager.MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none">
    </android.support.v4.view.ViewPager>
</RelativeLayout>

CustomPageAdapter.java

We are going to create a custom PagerAdapter class. This class will inherit from the android default PagerAdapter class and the following methods from the class will be overridden in the CustomPagerAdapter class.

In your package directory inside java folder, right click on the folder and choose create new file, select java file and name your file CustomPagerAdapter.java.

Open the newly created file and add the code below to the file.

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class CustomPageAdapter extends PagerAdapter {
    private Context context;
    private List<DataObject> dataObjectList;
    private LayoutInflater layoutInflater;
    public CustomPageAdapter(Context context, List<DataObject> dataObjectList){
        this.context = context;
        this.layoutInflater = (LayoutInflater)this.context.getSystemService(this.context.LAYOUT_INFLATER_SERVICE);
        this.dataObjectList = dataObjectList;
    }
    @Override
    public int getCount() {
        return dataObjectList.size();
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((View)object);
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = this.layoutInflater.inflate(R.layout.pager_list_items, container, false);
        ImageView displayImage = (ImageView)view.findViewById(R.id.large_image);
        TextView imageText = (TextView)view.findViewById(R.id.image_name);
        displayImage.setImageResource(this.dataObjectList.get(position).getImageId());
        imageText.setText(this.dataObjectList.get(position).getImageName());
        container.addView(view);
        return view;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}

pager_list_items.xml

you can see that we inflated a layout file which will represent the UI of each page in the ViewPager. So go to the layout folder, right click on the folder and select New > XML > layout file. Name this file pager_list_items.xml. The layout file will contain an ImageView and TextView controls.

Open this layout file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/large_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="30dp"
        android:src="@drawable/imageone"
        android:padding="16dp" />
    <TextView
        android:id="@+id/image_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        android:text="@string/app_name"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_below="@+id/large_image"/>
</RelativeLayout>

DataObject.java

We are going to make use of an Entity Object class we will name DataObject. This class will wrapper a resource id for the image and a string that will represent the image name. It will also contain getter and setter methods

Right click on the package folder and select a New file > java file. Name the file DataObject.java.

Open the newly created file and add the below code inside the file.

public class DataObject {
    private int imageId;
    private String imageName;
    public DataObject(int imageId, String imageName) {
        this.imageId = imageId;
        this.imageName = imageName;
    }
    public int getImageId() {
        return imageId;
    }
    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
    public String getImageName() {
        return imageName;
    }
    public void setImageName(String imageName) {
        this.imageName = imageName;
    }
}

MainActivity.java

Finally, open the MainActivity.java file, Inside the class, we will obtain the instances of the ViePager and CustomPagerAdapter.

We will create our data source by using a List<DataObject> that wraps a DataObject instance. We will pass the List object as one of the parameters in the CustomPagerAdapter.

The ViewPager object will call the setAdapter() method and the instance of the CustomPagerAdapter is passed as a parameter.

Open the file and add the code below to the file.

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        List<DataObject> getData = dataSource();
        viewPager = (ViewPager)findViewById(R.id.viewpager);
        CustomPageAdapter mCustomPagerAdapter = new CustomPageAdapter(MainActivity.this, getData);
        viewPager.setAdapter(mCustomPagerAdapter);
    }
    private List<DataObject> dataSource(){
        List<DataObject> data = new ArrayList<DataObject>();
        data.add(new DataObject(R.drawable.imageone, "Ferrari"));
        data.add(new DataObject(R.drawable.imagetwo, "BMW"));
        data.add(new DataObject(R.drawable.imagethree, "Bugatti"));
        return data;
    }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new android blog post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

2 Comments

Add a Comment