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 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.
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());
}
}
isViewFromObject
methodinstantiateItem
methodThe image below shows the app in action. This brings an end to ViewPager in android example tutorial. You can download the Android ViewPager Project from the below link.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
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.
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
How do i add activity to each fragment in the view pager?
- Dennis
Thank you! Really nice! Look at this library - https://github.com/Cleveroad/SlidingTutorial-Android
- Richard
Very helpful. But how i add more views(more than three). Please help me. I am a novice in android development.
- Ras
thanks …
- atefeh
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
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
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
Really Helpful Thanks
- Joginder Pal Verma
How to use OnItemClickListener with viewpager and get position of clicked item and displays the clicked item???
- Niks