How to switch between photos by swiping. (ViewPager)

While using android, one of the easiest, most user friendly ways of displaying multiple photos is by swiping a finger across the screen.  It has become common place to use this in an app for both android and ios, so how does one utilize this feature when creating their very own app for the android.  This feature is called a ViewPager.  “It is a layout manager that allows the user to flip left and right through pages of data.” – Android Developer website.

http://developer.android.com/reference/android/support/v4/view/ViewPager.html

Here is the website to everything that you will ever need to know about the ViewPager feature.  This includes a description of what it is, a list of all the functions that can be called , and another example it needed.  Now to get started writing this program you will need to create a new Android Application project, assuming you are using Eclipse, and set up this project to be a normal blank project.  For the purposes of this tutorial:

Application name: tutorialPager

Activity name: PagerMain

Layout name: pager_main


 

ViewPager will need no permissions to be added to the AndroidManifest.xml file so we can just leave that alone.  Lets first take a look at the res/layout/pager_main.xml file we have at start up.  You should have a classic Hello World relative layout.  We will not be needing the TextView so go ahead and delete that so you only have the Relative Layout that was originally given.  we will be adding the ViewPager to the layout which will be under android.support.v4.view.ViewPager.  It should look like this now.


<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.example.tutorialpager.PagerMain" >

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

</RelativeLayout>


 

Now the next step is to start creating the ViewPager adapter so that way when we call it in our main we will have something to use.  The adapter is specifically used to create and destroy the view as its being used or not being used.  This allows us to safeguard our memory and only use what is needed.  This is what makes ViewPager so powerful.  Now to start this off, inside your project create a new class.  For the purposes of this tutorial I have named mine DemoAdapter.


package com.example.tutorialpager;

import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class DemoAdapter extends PagerAdapter {

 Activity activity;
 int demoPhotoArray[]; //This array holds all the images for the demoAdapter

//====================Constructor===================
 public DemoAdapter(Activity act, int[] mainPhotoArray) {
 demoPhotoArray = mainPhotoArray;
 activity = act;
 }

//==================Get Array Size==================
 public int getCount() {
 return demoPhotoArray.length;
 }

//=================Instantiate Item=================
 public Object instantiateItem(View container, int position) {
 //Creates the page for that given position.
 ImageView view = new ImageView(activity);
 view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
 LayoutParams.MATCH_PARENT));
 view.setScaleType(ScaleType.FIT_XY);
 view.setBackgroundResource(demoPhotoArray[position]);
 ((ViewPager) container).addView(view, 0);
 return view;
 }

//=================Destroys the Item=================
 @Override
 public void destroyItem(View container, int position, Object object) {
 ((ViewPager) container).removeView((View) object);
 }

//=================Checks the Object=================
 @Override
 public boolean isViewFromObject(View view, Object object) {
 //makes sure that the page View is associated with a specific key
 // object returned by instantiateItem(View, int)
 return view == ((View) object);
 }
//=====================Save State=====================
 @Override
 public Parcelable saveState() {
 //Save any instance state associated with
 //this adapter and its pages that should be
 //restored if the current UI state needs to
 // be reconstructed.
 return null;
 }
}

 

 


Now that the adapter has been completed  lets use it.  But first we will need some images to slide through.  You may use whatever images you wish and however many, just make sure you place them in the res/drawable file.  Also make sure that each name of the picture are all lowercase letters or else you will have an error which will not allow you to run your program.

package com.example.tutorialpager;

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

public class PagerMain extends ActionBarActivity {

 DemoAdapter adapter;
 //Photos for the main that will be sent to the DemoAdapter
 private int mainPhotoArray[] = {
 R.drawable.image1, R.drawable.image2,
 R.drawable.image3};

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

 adapter = new DemoAdapter(this, mainPhotoArray);
 ViewPager pager = (ViewPager) findViewById(R.id.view_pager);
 pager.setAdapter(adapter);
 //This sets the first image you want to see and does not have to be 0
 //but must be 0 < image < image.size()
 pager.setCurrentItem(0);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 getMenuInflater().inflate(R.menu.pager_main, menu);
 return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 int id = item.getItemId();
 if (id == R.id.action_settings) {
 return true;
 }
 return super.onOptionsItemSelected(item);
 }
}

Now you have a working ViewPager that you can implement with any app you so desire.  
Please enjoy, share, and show off to all of your friends!!!