How to Display Image Gallery Using ViewPager in Android

Hi Everyone,

In this Blog Post i am going to brief about, how to display image gallery using ViewPager in android.


What is ViewPager?

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.

Let’s see how to display image gallery using Viewpager and PagerAdaptor in Android.

Step 1:

Create imageslider.xml in your ‘res/layout’ folder. Then copy and paste the following code.

< xmlns:android="" android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="match_parent">

Step 2:
Create in your project’s ‘src’ folder. Then copy and paste the following code.

public class ImageSlider extends Activity {
	int[] imageArray;
	Bundle bundle;
	final TypedArray imageArrayIcon=null;
	public void onCreate(Bundle savedInstanceState) {
		ViewPager viewPager = (ViewPager) findViewById(;
		ImagePagerAdapter adapter = new ImagePagerAdapter();
		//imageArrayIcon = getResources().obtainTypedArray(R.array.imageArray);

	private class ImagePagerAdapter extends PagerAdapter {
		private int[] mImages = new int[]{R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4};

		public int getCount() {
			return mImages.length;

		public boolean isViewFromObject(View view, Object object) {
			return view == ((ImageView) object);

		public Object instantiateItem(ViewGroup container, int position) {
			Context context = ImageSlider.this;
			ImageView imageView = new ImageView(context);
			int padding = context.getResources().getDimensionPixelSize(
			imageView.setPadding(padding, padding, padding, padding);
			//imageView.setImageResource(imageArrayIcon.getResourceId(mImages[position], -1));
			((ViewPager) container).addView(imageView, 0);
			return imageView;

		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((ImageView) object);

Step 3:
Now, you have to mention the padding for the images in your dimens.xml file. dimens.xml file will be in res/values/dimens.xml. If you dont have that file create it, and copy and paste the following code.

 <dimen name="padding_small">4dp</dimen>
 <dimen name="padding_medium">8dp</dimen>
 <dimen name="padding_large">16dp</dimen>

You can also display image from array.xml file using TypedArray
Thats it you got the image gallery. Happy coding

  1. manikandan

Leave a Reply

Your email address will not be published. Required fields are marked *