This tutorial explains how to build your own image gallery browser in your android applications with swipe and pinch zooming functionality. This article is combination of three separate concepts such as Grid View, Swiping and Pinch Gesture in one project.

I already covered Grid View previously. Refer Android GridView Layout Tutorial incase if you are new to Grid View.

android full screen image slider with swipe gesture

This project is divided in to three tasks. First one is building Grid View display of all the images. Second is showing selected grid image in full screen slider. And finally adding pinch zooming functionality to fullscreen image.

Let’s start with creating a new project

Creating new project

1. Create new project in Eclipse IDE from File ⇒ New ⇒ Android Application Project and fill all the required details. I kept my package name as info.androidhive.imageslider and main activity name as GridViewActivity.java

App Constant Class

I am creating a app constant class file to store static variables which will be used across application. In this way you don’t have modify much code if you want to change app configuration.

2. In order to maintaining good project structure I am creating a separate package for storing this kind of helper classes. Right click on src ⇒ New ⇒ Package and name it as your_package_name.helper.
(So my helper package becomes info.androidhive.imageslider.helper)

3. Under helper package create a new class named AppConstant.java and paste the following code. In the following I declared required constant variables

NUM_OF_COLUMNS – Number of columns to be displayed in Grid view
PHOTO_ALBUM – Name of the photo album directory in the sd card. Make sure that you have some images inside this directory before you start the project.
FILE_EXTN – Image file extensions to be supported

package info.androidhive.imageslider.helper;

import java.util.Arrays;
import java.util.List;

public class AppConstant {

	// Number of columns of Grid View
	public static final int NUM_OF_COLUMNS = 3;

	// Gridview image padding
	public static final int GRID_PADDING = 8; // in dp

	// SD card image directory
	public static final String PHOTO_ALBUM = "androidhive";

	// supported file formats
	public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
			"png");
}

Helper Utils Class

4. I am creating another class to define reusable functions across applications. Create another class under helper package named Utils.java

Following are major functions defined in Utils class

getFilePaths() – This function will return all image paths of a directory
IsSupportedFile() – This will check for supported file extensions

package info.androidhive.imageslider.helper;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

public class Utils {

	private Context _context;

	// constructor
	public Utils(Context context) {
		this._context = context;
	}

	// Reading file paths from SDCard
	public ArrayList<String> getFilePaths() {
		ArrayList<String> filePaths = new ArrayList<String>();

		File directory = new File(
				android.os.Environment.getExternalStorageDirectory()
						+ File.separator + AppConstant.PHOTO_ALBUM);

		// check for directory
		if (directory.isDirectory()) {
			// getting list of file paths
			File[] listFiles = directory.listFiles();

			// Check for count
			if (listFiles.length > 0) {

				// loop through all files
				for (int i = 0; i < listFiles.length; i++) {

					// get file path
					String filePath = listFiles[i].getAbsolutePath();

					// check for supported file extension
					if (IsSupportedFile(filePath)) {
						// Add image path to array list
						filePaths.add(filePath);
					}
				}
			} else {
				// image directory is empty
				Toast.makeText(
						_context,
						AppConstant.PHOTO_ALBUM
								+ " is empty. Please load some images in it !",
						Toast.LENGTH_LONG).show();
			}

		} else {
			AlertDialog.Builder alert = new AlertDialog.Builder(_context);
			alert.setTitle("Error!");
			alert.setMessage(AppConstant.PHOTO_ALBUM
					+ " directory path is not valid! Please set the image directory name AppConstant.java class");
			alert.setPositiveButton("OK", null);
			alert.show();
		}

		return filePaths;
	}

	// Check supported file extensions
	private boolean IsSupportedFile(String filePath) {
		String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
				filePath.length());

		if (AppConstant.FILE_EXTN
				.contains(ext.toLowerCase(Locale.getDefault())))
			return true;
		else
			return false;

	}

	/*
	 * getting screen width
	 */
	public int getScreenWidth() {
		int columnWidth;
		WindowManager wm = (WindowManager) _context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();

		final Point point = new Point();
		try {
			display.getSize(point);
		} catch (java.lang.NoSuchMethodError ignore) { // Older device
			point.x = display.getWidth();
			point.y = display.getHeight();
		}
		columnWidth = point.x;
		return columnWidth;
	}
}

Displaying thumbnail images in Grid View

Until now we are done with some utility functions which required further. So let’s start first view of the application which is displaying images in grid view.

5. Create a new layout file under res ⇒ layout folder named activity_grid_view.xml and paste the following code

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:stretchMode="columnWidth"
    android:background="#000000"> 
</GridView>

GridView Adapter

I am creating a custom grid adapter class for the grid view. In this way you can create a reusable view for the grid view blocks. As this class is not an activity class I prefer to keep it in another package.

6. Create another package named adapter under src folder. I created another package named info.androidhive.imageslider.adapter

7. Under adapter package create a class file named GridViewImageAdapter.java and extend it from BaseAdapter This adapter class simply returns image view to gridview.

package info.androidhive.imageslider.adapter;

import info.androidhive.imageslider.FullScreenViewActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class GridViewImageAdapter extends BaseAdapter {

	private Activity _activity;
	private ArrayList<String> _filePaths = new ArrayList<String>();
	private int imageWidth;

	public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
			int imageWidth) {
		this._activity = activity;
		this._filePaths = filePaths;
		this.imageWidth = imageWidth;
	}

	@Override
	public int getCount() {
		return this._filePaths.size();
	}

	@Override
	public Object getItem(int position) {
		return this._filePaths.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView;
		if (convertView == null) {
			imageView = new ImageView(_activity);
		} else {
			imageView = (ImageView) convertView;
		}

		// get screen dimensions
		Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
				imageWidth);

		imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
		imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
				imageWidth));
		imageView.setImageBitmap(image);

		// image view click listener
		imageView.setOnClickListener(new OnImageClickListener(position));

		return imageView;
	}

	class OnImageClickListener implements OnClickListener {

		int _postion;

		// constructor
		public OnImageClickListener(int position) {
			this._postion = position;
		}

		@Override
		public void onClick(View v) {
			// on selecting grid view image
			// launch full screen activity
			Intent i = new Intent(_activity, FullScreenViewActivity.class);
			i.putExtra("position", _postion);
			_activity.startActivity(i);
		}

	}

	/*
	 * Resizing image size
	 */
	public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
		try {

			File f = new File(filePath);

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			final int REQUIRED_WIDTH = WIDTH;
			final int REQUIRED_HIGHT = HIGHT;
			int scale = 1;
			while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
					&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
				scale *= 2;

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

}

8. Finally open the activity class for grid view. In my case my grid view activity name is GridViewActivity.java.

InitilizeGridLayout() – This will initialize the grid view layout by setting necessary attributes like padding, number of columns, spacing between grid images etc.,

package info.androidhive.imageslider;

import info.androidhive.imageslider.adapter.GridViewImageAdapter;
import info.androidhive.imageslider.helper.AppConstant;
import info.androidhive.imageslider.helper.Utils;

import java.util.ArrayList;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.TypedValue;
import android.widget.GridView;

public class GridViewActivity extends Activity {

	private Utils utils;
	private ArrayList<String> imagePaths = new ArrayList<String>();
	private GridViewImageAdapter adapter;
	private GridView gridView;
	private int columnWidth;

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

		gridView = (GridView) findViewById(R.id.grid_view);

		utils = new Utils(this);

		// Initilizing Grid View
		InitilizeGridLayout();

		// loading all image paths from SD card
		imagePaths = utils.getFilePaths();

		// Gridview adapter
		adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,
				columnWidth);

		// setting grid view adapter
		gridView.setAdapter(adapter);
	}

	private void InitilizeGridLayout() {
		Resources r = getResources();
		float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				AppConstant.GRID_PADDING, r.getDisplayMetrics());

		columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

		gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
		gridView.setColumnWidth(columnWidth);
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setPadding((int) padding, (int) padding, (int) padding,
				(int) padding);
		gridView.setHorizontalSpacing((int) padding);
		gridView.setVerticalSpacing((int) padding);
	}

}

Now run your project and test it once. You should see a grid view displaying the images from the sd card. Following is the screenshot of my grid view

android grid view and fullscreen image slider

Creating Fullscreen Image Slider

Second task in this tutorial is to build a fullscreen image slider for the images displayed in the grid view. This also involves swiping gesture to navigate through the album.

To create swiping gesture functionality I am using PagerAdapter class provided by android.

9. Create an xml layout file for full screen activity. I created a file called activity_fullscreen_view.xml under res ⇒ layout folder. Add a android.support.v4.view.ViewPager element inside it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>

10. In fullscreen view instead of showing only fullview image you might want to show some other UI elments like text, buttons along with the image. So I created a separate layout for fullscreen view, so that you can customize the fullscreen view in this layout file.

As of now I am just adding a close button over the image. Create an xml layout file under res ⇒ layout folder named layout_fullscreen_image.xml and add the following code

<?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/imgDisplay"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter" />

    <Button
        android:id="@+id/btnClose"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:paddingTop="2dp"
        android:paddingBottom="2dp"
        android:background="@drawable/button_background"
        android:textColor="#ffffff"
        android:text="Close" />

</RelativeLayout>

Also create a file called button_background.xml under drawable folder. This is just for styling the button

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners android:radius="3dp" />

    <solid android:color="#000000" />

    <stroke
        android:width="2px"
        android:color="#ffffff" />

</shape>

Fullscreen Image Viewer Adapter

Just like grid adapter, we are going to create another adapter for the full screen activity too. This is the data provider for the fullscreen image viewer.

11. Create another class under adapter package named FullScreenImageAdapter.java and extend it from PagerAdapter.

package info.androidhive.imageslider.adapter;

import info.androidhive.imageslider.R;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class FullScreenImageAdapter extends PagerAdapter {

	private Activity _activity;
	private ArrayList<String> _imagePaths;
	private LayoutInflater inflater;

	// constructor
	public FullScreenImageAdapter(Activity activity,
			ArrayList<String> imagePaths) {
		this._activity = activity;
		this._imagePaths = imagePaths;
	}

	@Override
	public int getCount() {
		return this._imagePaths.size();
	}

	@Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }
	
	@Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imgDisplay;
        Button btnClose;
 
        inflater = (LayoutInflater) _activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
                false);
 
        imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);
        btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
        
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
        imgDisplay.setImageBitmap(bitmap);
        
        // close button click event
        btnClose.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				_activity.finish();
			}
		});
 
        ((ViewPager) container).addView(viewLayout);
 
        return viewLayout;
	}
	
	@Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((RelativeLayout) object);
 
    }
}

Also make sure that you have added FullScreenViewActivity to AndroidManifest.xml file before testing your project.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.imageslider"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.imageslider.GridViewActivity"
            android:theme="@android:style/Theme.Holo.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity
            android:name="info.androidhive.imageslider.FullScreenViewActivity"
            android:theme="@android:style/Theme.Holo.NoActionBar">
        </activity>
    </application>

</manifest>

Run your project once again and click on grid view image. You should see fullscreen view of selected grid view image. Also swipe left or right to cycle through album.

android full screen image slider with swipe

Adding Pinch Zooming Functionality

For pinching functionality instead of writing my own class from scratch, I just borrowed the code from TouchImageView. Thanks to Michael Ortiz for writing such a beautiful code 🙂

Adding this class in your project needs very few modifications.

12. Create class in helper package named TouchImageView.java and paste the following code.

package info.androidhive.imageslider.helper;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;

public class TouchImageView extends ImageView {

	Matrix matrix;

	// We can be in one of these 3 states
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;

	// Remember some things for zooming
	PointF last = new PointF();
	PointF start = new PointF();
	float minScale = 1f;
	float maxScale = 3f;
	float[] m;

	int viewWidth, viewHeight;
	static final int CLICK = 3;
	float saveScale = 1f;
	protected float origWidth, origHeight;
	int oldMeasuredWidth, oldMeasuredHeight;

	ScaleGestureDetector mScaleDetector;

	Context context;

	public TouchImageView(Context context) {
		super(context);
		sharedConstructing(context);
	}

	public TouchImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		sharedConstructing(context);
	}

	private void sharedConstructing(Context context) {
		super.setClickable(true);
		this.context = context;
		mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
		matrix = new Matrix();
		m = new float[9];
		setImageMatrix(matrix);
		setScaleType(ScaleType.MATRIX);

		setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				mScaleDetector.onTouchEvent(event);
				PointF curr = new PointF(event.getX(), event.getY());

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					last.set(curr);
					start.set(last);
					mode = DRAG;
					break;

				case MotionEvent.ACTION_MOVE:
					if (mode == DRAG) {
						float deltaX = curr.x - last.x;
						float deltaY = curr.y - last.y;
						float fixTransX = getFixDragTrans(deltaX, viewWidth,
								origWidth * saveScale);
						float fixTransY = getFixDragTrans(deltaY, viewHeight,
								origHeight * saveScale);
						matrix.postTranslate(fixTransX, fixTransY);
						fixTrans();
						last.set(curr.x, curr.y);
					}
					break;

				case MotionEvent.ACTION_UP:
					mode = NONE;
					int xDiff = (int) Math.abs(curr.x - start.x);
					int yDiff = (int) Math.abs(curr.y - start.y);
					if (xDiff < CLICK && yDiff < CLICK)
						performClick();
					break;

				case MotionEvent.ACTION_POINTER_UP:
					mode = NONE;
					break;
				}

				setImageMatrix(matrix);
				invalidate();
				return true; // indicate event was handled
			}

		});
	}

	public void setMaxZoom(float x) {
		maxScale = x;
	}

	private class ScaleListener extends
			ScaleGestureDetector.SimpleOnScaleGestureListener {
		@Override
		public boolean onScaleBegin(ScaleGestureDetector detector) {
			mode = ZOOM;
			return true;
		}

		@Override
		public boolean onScale(ScaleGestureDetector detector) {
			float mScaleFactor = detector.getScaleFactor();
			float origScale = saveScale;
			saveScale *= mScaleFactor;
			if (saveScale > maxScale) {
				saveScale = maxScale;
				mScaleFactor = maxScale / origScale;
			} else if (saveScale < minScale) {
				saveScale = minScale;
				mScaleFactor = minScale / origScale;
			}

			if (origWidth * saveScale <= viewWidth
					|| origHeight * saveScale <= viewHeight)
				matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
						viewHeight / 2);
			else
				matrix.postScale(mScaleFactor, mScaleFactor,
						detector.getFocusX(), detector.getFocusY());

			fixTrans();
			return true;
		}
	}

	void fixTrans() {
		matrix.getValues(m);
		float transX = m[Matrix.MTRANS_X];
		float transY = m[Matrix.MTRANS_Y];

		float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
		float fixTransY = getFixTrans(transY, viewHeight, origHeight
				* saveScale);

		if (fixTransX != 0 || fixTransY != 0)
			matrix.postTranslate(fixTransX, fixTransY);
	}

	float getFixTrans(float trans, float viewSize, float contentSize) {
		float minTrans, maxTrans;

		if (contentSize <= viewSize) {
			minTrans = 0;
			maxTrans = viewSize - contentSize;
		} else {
			minTrans = viewSize - contentSize;
			maxTrans = 0;
		}

		if (trans < minTrans)
			return -trans + minTrans;
		if (trans > maxTrans)
			return -trans + maxTrans;
		return 0;
	}

	float getFixDragTrans(float delta, float viewSize, float contentSize) {
		if (contentSize <= viewSize) {
			return 0;
		}
		return delta;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		viewWidth = MeasureSpec.getSize(widthMeasureSpec);
		viewHeight = MeasureSpec.getSize(heightMeasureSpec);

		//
		// Rescales image on rotation
		//
		if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
				|| viewWidth == 0 || viewHeight == 0)
			return;
		oldMeasuredHeight = viewHeight;
		oldMeasuredWidth = viewWidth;

		if (saveScale == 1) {
			// Fit to screen.
			float scale;

			Drawable drawable = getDrawable();
			if (drawable == null || drawable.getIntrinsicWidth() == 0
					|| drawable.getIntrinsicHeight() == 0)
				return;
			int bmWidth = drawable.getIntrinsicWidth();
			int bmHeight = drawable.getIntrinsicHeight();

			Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);

			float scaleX = (float) viewWidth / (float) bmWidth;
			float scaleY = (float) viewHeight / (float) bmHeight;
			scale = Math.min(scaleX, scaleY);
			matrix.setScale(scale, scale);

			// Center the image
			float redundantYSpace = (float) viewHeight
					- (scale * (float) bmHeight);
			float redundantXSpace = (float) viewWidth
					- (scale * (float) bmWidth);
			redundantYSpace /= (float) 2;
			redundantXSpace /= (float) 2;

			matrix.postTranslate(redundantXSpace, redundantYSpace);

			origWidth = viewWidth - 2 * redundantXSpace;
			origHeight = viewHeight - 2 * redundantYSpace;
			setImageMatrix(matrix);
		}
		fixTrans();
	}
}

13. After adding the class open your layout_fullscreen_image.xml file which used to display fullscreen image and modify ImageView to info.androidhive.imageslider.helper.TouchImageView element.

<?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" >

    <info.androidhive.imageslider.helper.TouchImageView
        android:id="@+id/imgDisplay"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter" />

    <Button
        android:id="@+id/btnClose"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:paddingTop="2dp"
        android:paddingBottom="2dp"
        android:background="@drawable/button_background"
        android:textColor="#ffffff"
        android:text="Close" />

</RelativeLayout>

14. In FullScreenImageAdapter.java class also we used ImageView. Just replace this one with TouchImageView

public class FullScreenImageAdapter extends PagerAdapter {
	.
	.
	.	
	@Override
    public Object instantiateItem(ViewGroup container, int position) {
        TouchImageView imgDisplay; // Replace here with TouchImageView
	.
	// this one too
        imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay); // this one too
	.
	.
	.
 
        return viewLayout;
	}
}

Run your project now and test the pinch zooming functionality.

Testing Pinch Zooming in Emulator

As of now Emulator is not supporting multi touch gesture. So you should use real device to test the pinch zooming functionality

I know this project has some performance issues like grid scrolling is little bit slow. Search and try to find a solution to make it better.

Happy Coding …. 🙂

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • samir

    thanks for uploading………..

  • nirmal

    very nice

  • iMaulik

    great! & thanks

  • Costis

    It is not running.
    There is a message:
    “NAT directory path is not valid
    Please set the image directory
    name AppConstant.java class”

    How can I set the directory in the emulator???????
    thanks

    • You should keep a image album name in AppConstant.java class. Load some images in sdcard and give the folder name in AppConstatn.java class.

      In Eclipse use DDMS tool to create folder and push some images into it.

      • Costis

        Thanks!!
        ..and congratulations for Androidhive
        the best android site ever!!

      • partha

        can you tell me how can i do that

      • ravikant

        hii plz tell me how creat foldr in DDMS tool and then how set the path of PHOTO_ALBUM=””

  • Piter

    “NAT directory path is not valid
    Please set the image directory
    name AppConstant.java class” 🙁

    • You should keep a image album name in AppConstant.java class. Load some images in sdcard and give the folder name in AppConstatn.java class.

      • Siva

        Hi i have the viewpager to show the image and how can i implement the TouchImageView class into viewpager in my code

      • vineet

        hi ravi,this app is running bt when images are load and show in gridview after that when i touch the image than nothing was happen..

  • gunz

    How can i aoutomatically create folder “NAT” and add image to that folder.?

  • Nijo George P

    I have developed a file manager application. Is it possible to integrate this image slider app with my file manager?

  • Nirmal Revar

    public static final String PHOTO_ALBUM = “Images”;

    just Simply Write Your Album folder name,,and make sure that album has to be in Phone Memory,if that album is in SD card then it will not work…..

    • Thanks Nirmal for explaining this. I already did mentioned this but not many people are noticing 🙂

      • Nirmal Revar

        Ya ,u r right ..

      • Costis

        What about when I want to show in the application fotos from res -> drawable folder???

        • Yeah. I also want to load from res folder? How can I do that? Anyone?

          • Kutalp*DH

            Hey ravi i need that too how can us do that?

  • baha_odeh

    Nice tutorial bro , but why you didn’t use PhotoView to support zoom ?
    try it
    https://github.com/chrisbanes/PhotoView
    its very nice and clean

  • Antony Kor

    Excellent tutorial Ravi, thanks once again 🙂

    • You are welcome 🙂

      • JMarv

        Hello.. I’m newbie in android programming.. My concern is what’s the use of FullScreenViewActivity because I confuse on it. In your given code I don’t get the function of this class FullScreenViewActivity.. I test this code but got me error in displaying the full-screen image.. Thanks in advance.. ^_^

  • Christopher J

    Thanks a lot. this is exactly what I was looking for.

  • partha

    my images are in DCIM/Camera folder , what code can i write , so that i got the images from the specified folder

    • Then use this in AppConstant.java

      public static final String PHOTO_ALBUM = “DCIM/Camera”; and try

  • Thanks!

    I launched it and the everything loads great, however its lags on scrolling up and down on grid view and the images dont auto-rotate to their taken layout (portrait/landscape) Is this the intended result?

    Edit: I’m also getting crashes on the device (below) and Nexus 4 (Emulator) I checked the log OutOfMemory

    On a Galaxy S 4 Google Edition GT-i9505G (4.3)

  • billy

    Hi, may I know if it is possible to load the image from the Asset folder instead of load the image from SD card?
    Thanks in advance.

  • Very nice Tutorial… How to load images from url links?

  • Karan

    Hi.. I loved this Application. But it gives Error on Galaxy Tab2. After swiping the image 2-3 times, it Force Closes. It works fine on Xperia U.
    Please have a look.

  • JMarv

    Hello.. I’m newbie in android programming.. My concern is what’s the use of FullScreenViewActivity because I confuse on it. In your given code I don’t get the function of this class FullScreenViewActivity.. I test this code but got me error in displaying the full-screen image.. Thanks in advance.. ^_^ God bless…

  • Omi

    Thank You Ravi for such a great app.
    I have to swipe between different layouts? how to do it can you please explain

  • ravikant

    plzz tell me yaarr I took all effort bt the problm is nt solved…. i m using android emulator in eclipse and how and where to set path for memory…. 🙁

  • Wayan

    hey Ravi, where is FullScreenViewActivity.java ? can you tell me?

    • src > info.androidhive.imageslider > FullScreenViewActivity.java

  • Tulai Paul

    Extensive article with full of fertility. The codes will surely help the mobile apps and games developers. We hope that availability of such free codes will not provoke the companies like admob or revmob or adcolony or appnext to reduce their ecpm.

  • Guest

    whr can i download source code zip ravi bro??

  • Guest

    i downloaded the source code as zip , and installed the source code from here. and when i run this app, there is pop up window appears and shows”NAT directory path is not valid! Please set the image directory name AppConstant.java class”

    wat can i do for this ravi bro??

    • In AppConstant.java class:

      Change “NAT” to the preferred location (like for example the bluetooth folder):
      public static final String PHOTO_ALBUM = “bluetooth”;

      • vineet

        hey i’m using DDMS than where i can stored the images …??

        • Sorry. I’m using the real device. No clue on the emulator.

          • vineet

            its ok aisha but can u plz tell me thz …,this app is running bt when images are load and show in gridview
            after that when i touch the image than nothing was happen..

          • Shashiraj

            Same error here when i run this app on emulator. What may be the solution? Pls suggest…:)

          • Diviya

            Same error, While running in phone I got only the gridview. If I click any image in gridview its showing me error that your application have been stopped unexceptly.

        • Push images in data folder for emulator.

  • Guest

    i dont understand your reply bro”You should keep a image album
    name in AppConstant.java class. Load some images in sdcard and give the
    folder name in AppConstatn.java class.

    In Eclipse use DDMS tool to create folder and push some images into it.” need more clear info bro, please elaborate it ravi bro….

    • You must have to that folder in your SD card.

      otherwise change folder name in which you have some photos.

      AppConstant.java->PHOTO_ALBUM.

  • KP Ranjith

    Bro pls tell me if there is any job vacancy for android developer fresher… pls mail me at ranjithstar256@gmail.com Thank You Bro….

  • Pushkar Pandey

    Oops!

    Hi Ravi!. By mistake i submitted the comment in the above bug report section. Please ignore that.

    Thank you.

  • Pushkar Pandey

    Hi Ravi!
    Nice article. I’m a regular follower of your blog.

    I have used Michael Ortiz pinch-zoom code in my project. Everything works just fine as expected with one minor issue.

    My image is supposed to be a full-screen (screen-fit) which i was able to do by using scaleType:fitxy in my layout xml. But after the TouchImageView integration, my imageview is not screen-fit anymore. It seems scaleType:fitxy is getting overridden my ScaleType.MATRIX in the TouchImageView.java code.

    My viewpager implementation is little different from yours. I’m reading & setting the bitmaps in the onCreateView() method of my FullScreenFragment.java which is a Fragment class being instantiated in the getItem() method of MyPagerAdapter inner class in my FullScreenActivity.java.

    Also, in my FullScreenActivity.java I’m using..

    myAdapter = new MyPagerAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(myAdapter);

    //(where MyPagerAdapter is a inner class in my FullScreenActivity.java )

    instead of ….

    adapter = new FullScreenImageAdapter(FullScreenViewActivity.this, utils.getFilePaths());
    viewPager.setAdapter(adapter);

    /* MyPagerAdapter inner class*/

    public class MyPagerAdapter extends FragmentStatePagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
    super(fm);
    }

    @Override
    public Fragment getItem(int position) {
    Fragment fragment = new FullScreenFragment();
    Bundle args = new Bundle();
    args.putInt(“page”, (position));
    args.putStringArray(“imageArray”, images);
    global = new Bundle();
    global.putInt(“page”, (position));
    fragment.setArguments(args);
    return fragment;
    }

    @Override
    public int getCount() {
    return GlobalState.slides.size(); // No. of pages.
    }

    }

    Hope I’m clear about the question & description. I’ll really appreciate your help.

    Thank you.

  • Guest

    Hi Ravi,
    Can i open images which is stored in Bluetooth folder in memory card(path:sdcard/bluetooth)?

    • Yeah. In AppConstant.java, change the directory to:

      public static final String PHOTO_ALBUM = “bluetooth”;

  • fadil p

    It is working for me…great tutorial
    Thanks Ravi..

  • iTechniqz

    See grid view type Android App

    Animal Sounds For Kids

    https://play.google.com/store/apps/details?id=com.itechniqz.animalsounds

  • RJ

    hey Ravi, Very nice tutorial and worked fine for me. But my further more requirement is that when Image is display in a full screen and if any user tap on image one button should visible true. i just want to set up click event on it. how it should be done? can u guide me please

  • Pushkar

    Hi Ravi! I’m facing an issue with a similar zoom functionality. Would really appreciate if you can take out time to check out my question at http://stackoverflow.com/questions/19155952/setting-boundary-limits-for-panning-dragging-a-zoomable-custom-relative-layout .

    Thanks

  • Dami

    Excellent tutorial!!! But, could you add a thread for the gridview loader?

  • Maringote

    can i have a question ? I’m curious how would the code look when i want to add this to tab fragment.

    • Maringote

      never mind, I managed it somehow 🙂

  • krishna

    cannot find the code for FullScreenViewActivity.java

  • Guest

    cannot find code for FullScreenViewActivity.java in this page

  • Kutalp*DH

    What about when I want to show in the application fotos from res -> drawable folder???

  • Green

    During trial run in actual Samsung device, get a print in the Logcat –
    Not a DRM file, opening normally
    buffer returned
    Any ideal to solve it?

  • joy

    hi, where is the FullScreenViewActivity.java code?
    I can not sign up, I did not receive verification email…

    please help me…..

    10x

  • Kutalp*DH

    What about when I want to show in the application fotos from res -> drawable folder???

  • What about when I want to show in the application photo from res / drawable folder? please!!

  • reza

    Is it possible to get the
    value in viewpagers widget just like the one in listview ?

    I have used the SharedPreferences to get access to widget’s inside value in
    viewpager.

    I have shared my problem in this link but it’s
    not solved

    http://stackoverflow.com/questions/19345628/getting-the-value-inside-the-widget-in-viewpager

    The problem is that when getting back from the viewpager’s
    “n” page (sliding to right) it return’s the value of the n+1 page. But it
    should return the n-1 ‘s value. But it’s working fine for the other pages.

  • w3i

    Thank you so much! You save my days of coding!

  • atomnet

    Hello,
    is possible load image from server?

    Thanks for tutorial.

  • Steve

    Ravi,
    This is exactly what I have been looking for!! Thank you so much for sharing. I was hoping you could help me with “deleting the image once selected. I have this code

    UPDATE **
    With some help from Stack Overflow i got the String I needed
    I Added the following to onCreate…

    String path = adapter._imagePaths.get(viewPager.getCurrentItem());

    which allowed me to create my fileDelete Method

    • amy

      File file = new File(selectedFilePath);
      boolean deleted = file.delete();

  • Vinod Rajan

    Hi Ravi,
    Thanks for giving a nice tutorial, you have done a wonderful job for people who learning android.

    I have one doubt.

    How we can add title to image in the gridview.

    • Imran

      Hi Vinod,

      You can inflate your own layout inside Grid Adapter
      view = inflater.inflate(R.layout.grid_image_item, parent, false);

      grid_image_item contains Image and Text

      • Vinod Rajan

        Thanks Imran,

        It got worked.

  • How can i use Images from Database in ViewPager.

  • Steve

    Hey Ravi,

    Do you have a fix for the Panning issue when the image is zoomed? I found that if you press on the image and move up and then over it pans the image. For whatever reason, it’s acting as if it doesn’t know the state of the image is “ZOOM”

    UPDATE…
    After a week of searching and trial and error, i finally found a solution for Panning as well as adding and Double Tap for Zoom in and Zoom out. It’s a bit messy, not perfect, but works.

    Here is the Updates TouchImageView.java file

    package info.androidhive.imageslider.helper;

    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.graphics.Matrix;
    import android.graphics.PointF;
    import android.graphics.drawable.Drawable;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.GestureDetector;
    import android.view.GestureDetector.SimpleOnGestureListener;
    import android.view.MotionEvent;
    import android.view.ScaleGestureDetector;
    import android.view.View;
    import android.widget.ImageView;

    //Original
    public class TouchImageView extends ImageView {

    Matrix matrix;

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF last = new PointF();
    PointF start = new PointF();
    float saveScale = 1f;
    float minScale = saveScale;
    float maxScale = 10f;
    float[] m;

    int viewWidth, viewHeight;
    static final int CLICK = 3;

    protected float origWidth, origHeight;
    int oldMeasuredWidth, oldMeasuredHeight;

    ScaleGestureDetector mScaleDetector;
    private GestureDetector gestureDetector;

    Context context;

    public TouchImageView(Context context) {
    super(context);
    sharedConstructing(context);
    }

    public TouchImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    sharedConstructing(context);
    }

    private void sharedConstructing(Context context) {
    gestureDetector = new GestureDetector(new DoubleTapGestureListener());
    super.setClickable(true);
    this.context = context;
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());

    matrix = new Matrix();
    m = new float[9];
    setImageMatrix(matrix);
    setScaleType(ScaleType.MATRIX);

    setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

    if (saveScale > 1f) {
    getParent().requestDisallowInterceptTouchEvent(true);
    } else {
    getParent().requestDisallowInterceptTouchEvent(false);
    }

    gestureDetector.onTouchEvent(event);

    mScaleDetector.onTouchEvent(event);
    PointF curr = new PointF(event.getX(), event.getY());

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
    if (mode == ZOOM) {
    //mode = DRAG;
    last.set(curr);
    start.set(last);
    } else {
    last.set(curr);
    start.set(last);
    mode = DRAG;
    }
    break;

    case MotionEvent.ACTION_MOVE:
    if (mode == DRAG) {
    float deltaX = curr.x – last.x;
    float deltaY = curr.y – last.y;
    float fixTransX = getFixDragTrans(deltaX, viewWidth,
    origWidth * saveScale);
    float fixTransY = getFixDragTrans(deltaY, viewHeight,
    origHeight * saveScale);
    matrix.postTranslate(fixTransX, fixTransY);
    fixTrans();
    last.set(curr.x, curr.y);
    }
    break;

    case MotionEvent.ACTION_UP:
    mode = NONE;
    int xDiff = (int) Math.abs(curr.x – start.x);
    int yDiff = (int) Math.abs(curr.y – start.y);
    if (xDiff < CLICK && yDiff minScale) {
    zoomOut();
    } else {
    zoomIn();
    }
    return true;
    }

    }

    float oldScale = 1f;

    public boolean isZoomed() {
    return saveScale > minScale; // this seems to work
    }

    @SuppressLint(“WrongCall”)
    public void zoomIn() {
    //LogUtil.i(TAG, “Zooming in”);
    oldScale = saveScale;
    saveScale *= 6f;
    matrix.setScale(saveScale, saveScale);
    setImageMatrix(matrix);
    onMeasure(viewHeight, viewWidth);
    invalidate();

    }

    @SuppressLint(“WrongCall”)
    public void zoomOut() {
    //LogUtil.i(TAG, “Zooming out”);
    saveScale = oldScale;
    matrix.setScale(saveScale, saveScale);
    setImageMatrix(matrix);
    onMeasure(oldMeasuredHeight, oldMeasuredWidth);
    invalidate();

    }

    public void setMaxZoom(float x) {
    maxScale = x;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
    mode = ZOOM;
    return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
    float mScaleFactor = detector.getScaleFactor();
    float origScale = saveScale;
    saveScale *= mScaleFactor;
    if (saveScale > maxScale) {
    saveScale = maxScale;
    mScaleFactor = maxScale / origScale;
    } else if (saveScale < minScale) {
    saveScale = minScale;
    mScaleFactor = minScale / origScale;
    }

    if (origWidth * saveScale <= viewWidth
    || origHeight * saveScale <= viewHeight)
    matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
    viewHeight / 2);
    else
    matrix.postScale(mScaleFactor, mScaleFactor,
    detector.getFocusX(), detector.getFocusY());

    fixTrans();
    return true;
    }
    }

    void fixTrans() {
    matrix.getValues(m);
    float transX = m[Matrix.MTRANS_X];
    float transY = m[Matrix.MTRANS_Y];

    float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
    float fixTransY = getFixTrans(transY, viewHeight, origHeight
    * saveScale);

    if (fixTransX != 0 || fixTransY != 0)
    matrix.postTranslate(fixTransX, fixTransY);
    }

    float getFixTrans(float trans, float viewSize, float contentSize) {
    float minTrans, maxTrans;

    if (contentSize <= viewSize) {
    minTrans = 0;
    maxTrans = viewSize – contentSize;
    } else {
    minTrans = viewSize – contentSize;
    maxTrans = 0;
    }

    if (trans maxTrans)
    return -trans + maxTrans;
    return 0;
    }

    float getFixDragTrans(float delta, float viewSize, float contentSize) {
    if (contentSize <= viewSize) {
    return 0;
    }
    return delta;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    //
    // Rescales image on rotation
    //
    if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
    || viewWidth == 0 || viewHeight == 0)
    return;
    oldMeasuredHeight = viewHeight;
    oldMeasuredWidth = viewWidth;

    if (saveScale == 1) {
    // Fit to screen.
    float scale;

    Drawable drawable = getDrawable();
    if (drawable == null || drawable.getIntrinsicWidth() == 0
    || drawable.getIntrinsicHeight() == 0)
    return;
    int bmWidth = drawable.getIntrinsicWidth();
    int bmHeight = drawable.getIntrinsicHeight();

    Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);

    float scaleX = (float) viewWidth / (float) bmWidth;
    float scaleY = (float) viewHeight / (float) bmHeight;
    scale = Math.min(scaleX, scaleY);
    matrix.setScale(scale, scale);

    // Center the image
    float redundantYSpace = (float) viewHeight
    – (scale * (float) bmHeight);
    float redundantXSpace = (float) viewWidth
    – (scale * (float) bmWidth);
    redundantYSpace /= (float) 2;
    redundantXSpace /= (float) 2;

    matrix.postTranslate(redundantXSpace, redundantYSpace);

    origWidth = viewWidth – 2 * redundantXSpace;
    origHeight = viewHeight – 2 * redundantYSpace;
    setImageMatrix(matrix);
    }
    fixTrans();
    }
    }

    I hope it helps someone else.

    -Steve

    • sara

      Hi Steve,
      Could you please help me?
      I want to zoom in the axis of photo that i double click on it, how should i do it?

  • Kwstas Antoniou

    Its Laggy when i load image to fullscreen ?

  • karan shah

    hello sir your tutorial is so good. i really inspire from your tutorial.
    i want only one thing. in this tutorial how i get images from internal
    storage. means i want to get all images from raw folder ya assets
    folder. i want to give images in build in my application.

  • stevepinero

    hello, when i swipe many images, the decodefile method raise an exception Out of memory. How can solve this? many images have dieferent resolutions

  • Valetto Pereira

    I want to make set as wallpaper in the full screen image view class i made a menu but cant understand how to set the image path as wallpaper please help me h

    • Sohail Zahid

      Bitmap bmp;
      InputStream is = getResources().openRawResource(R.drawable.icon);
      bmp = BitmapFactory.decodeStream(is);

      try {
      getApplicationContext().setWallpaper(bmp);
      } catch (IOException e) {
      e.printStackTrace();
      }

      this will set you pics as wallpaper…..if its not let me now on fb
      https://www.facebook.com/rangbazii

  • delph

    Hi !
    I found a little bug in the app… when you click on the first little one, the full screen doesn’t appear. You have to click on any other little one. After that the first one appear over the second one so you have to close the first one to see the second one!

    But if you start with any other picture (not the position ==0) everything is okay !

    Do you know how to change it to have a normal behaviour for the picture 0 ?
    Thanks !

    • Jean Pierre

      Jean Pierre

      remove the class OnImageClickListener from GridViewImageAdapter

      and the call of this class :

      imageView.setOnClickListener(new OnImageClickListener(position));

      add this code in GridViewActivity after gridView.setAdapter(adapter);

      gridView.setOnItemClickListener(new OnItemClickListener() {

      public void onItemClick(AdapterView parent, View v, int position, long id) {

      //Toast.makeText(GridViewActivity.this, “” + position, Toast.LENGTH_SHORT).show();

      Intent i = new Intent(GridViewActivity.this, FullScreenViewActivity.class);

      i.putExtra(“position”, position);

      GridViewActivity.this.startActivity(i);

      }

      });

      • soft xm

        Hi , I’ve tried your way but no method exists OnImageClickListener with ImageView

  • zeeshi

    when app is in grid view and and images are in grid view and i click n image for full screen image generates error that full screen slider stopped.. so plz help me..

  • zeeshi

    hi ravi this tutorial is very good and app working nicely but i we want t crop an image in this how we can do it. its a free hand cropping. After cropping the image we have to save it. Code

    protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(scaledBitmap, 0, 0,null);
    path.reset();
    boolean firstTouchPoint = true;
    for (int i = 0; i < lastPath.size(); i += 2) {
    Point point = lastPath.get(i);
    if (firstTouchPoint) {
    firstTouchPoint = false; path.moveTo(point.fXPosition,point.fYPosition);
    } else if
    (i < lastPath.size() – 1) { Point next = lastPath.get(i + 1);
    path.quadTo(point.fXPosition, point.fYPosition, next.fXPosition, next.fYPosition);
    }
    else
    {
    path.lineTo(point.fXPosition, point.fYPosition);
    }
    }
    canvas.drawPath(path, paint);
    }
    \ but I am not able to extract the bitmap region inside this path.

  • Bharat

    Out of memory exception

    12-09 17:41:00.485: E/AndroidRuntime(14155): java.lang.OutOfMemoryError

    12-09 17:41:00.485: E/AndroidRuntime(14155): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

    12-09 17:41:00.485: E/AndroidRuntime(14155): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:619)

    12-09 17:41:00.485: E/AndroidRuntime(14155): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:385)

    12-09 17:41:00.485: E/AndroidRuntime(14155): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:418)

    12-09 17:41:00.485: E/AndroidRuntime(14155): at info.androidhive.imageslider.adapter.FullScreenImageAdapter.instantiateItem(FullScreenImageAdapter.java:59)

    12-09 17:41:00.485: E/AndroidRuntime(14155): at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:829)

  • Harasemiuc Andrei

    Hello!

    Thank you for your post!

    I have to ask you something though.
    Can you please explain to me what is going on in the InitilizeGridLayout() method please?
    I tried documenting about Resource and TypedValue and so on, but I can’t understand.

    Why don’t you just use xml for defining the grid layout?
    Why is this better? etc.
    Please explain to me like a noob 😀

    Thanks!

    • Its because we want to make grid layout more dynamic. We have already declared number of columns, padding in constant file. Also we calculated column width dynamically (which differs in landscape mode). So If you want to change these value at any time, you can do it easily which is not possible if you define in xml layout.

      • Harasemiuc Andrei

        Thank you! I managed to undestand!

        Also I noticed that you forgot to add the code from FullScreenImageActivity.java to this post. I tried to write it myself but couldn’t manage it. Could you please post it?

        • Oh, I forgot. I’ll post the code

          • Harasemiuc Andrei

            Thank you! Hope you add it soon!

          • danman

            Ravi, your performance issue is with grid layout. I used grid view and its much faster. Grid views are specifically meant to work with adapters and the performance difference is quite noticeable

  • Max

    How can I integrate this Slider in my app?

  • Mario

    Hey, How can i download the code? It redirects me to an empty page. It’s to find FullScreenViewActivity since i don’t see it in the post.

  • Ghufran Mehmood

    sir plz help me how to improve performance i really need this image slider

  • sohel

    How to fetch all images from root directory “/mnt/”

  • Ruchina

    How to get images from internet to be in the gallery?

    • uky

      guyk

  • Kunu

    I am having problem in setting the NAT directory path. Can you please help me to short out this problem.

    • zia

      put a directory named as NAT in your phone or emulator’s sdcard, put images in that directory
      n the code will run fine

  • zia

    Thanks a lot man. nice code

  • Nilesh

    Please help..getting this error..:(

    01-09 15:12:13.706: E/AndroidRuntime(13744): FATAL EXCEPTION: main

    01-09 15:12:13.706: E/AndroidRuntime(13744): java.lang.OutOfMemoryError

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:663)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:392)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at info.androidhive.imageslider.adapter.FullScreenImageAdapter.instantiateItem(FullScreenImageAdapter.java:58)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:829)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.support.v4.view.ViewPager.populate(ViewPager.java:1044)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.support.v4.view.ViewPager.populate(ViewPager.java:911)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.View.measure(View.java:15557)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5114)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.View.measure(View.java:15557)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5114)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.View.measure(View.java:15557)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5114)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.View.measure(View.java:15557)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5114)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2397)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.View.measure(View.java:15557)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1242)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1417)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1135)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4579)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.Choreographer.doCallbacks(Choreographer.java:555)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.Choreographer.doFrame(Choreographer.java:525)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.os.Handler.handleCallback(Handler.java:615)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.os.Handler.dispatchMessage(Handler.java:92)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.os.Looper.loop(Looper.java:137)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at android.app.ActivityThread.main(ActivityThread.java:4935)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at java.lang.reflect.Method.invokeNative(Native Method)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at java.lang.reflect.Method.invoke(Method.java:511)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)

    01-09 15:12:13.706: E/AndroidRuntime(13744): at dalvik.system.NativeStart.main(Native Method)

  • senthilkumar

    where FullScreenViewActivity Class

  • San T

    Hi Ravi, I am getting a FileNotFoundException while I select an Image in GridView. Any insights on what might be causing it ?

  • Soheil Afshari

    Hi ravi nice tutorial . i have one question if i want to load images which within the program like in assets folder what should i do ?

    should i changeh ? final String PHOTO_ALBUM if yes to what ? tnx

  • Alexander Bolaños

    i cant find FullScreenViewActivity help me :S

    • Vivian Ambrose

      Download the source code and browse

      • Alexander Bolaños

        thanks, i didnt see the download button, but now i got a problem. The app open and everything, but when i click some picture for the zoom, the app stop and i dont now why :S

  • Christian Gomez

    What would have to change in method public ArrayList getFilePaths() to get pictures of assets?

  • Alexander Bolaños

    i got a problem. The app open and i can see the pictures and everything, but when i click some picture for the zoom, the app stop and i dont now why :S can you help me?

  • Jeffy

    how can i use this code to view photos from “drawable” and viewing the output on emulator?

  • sara

    hey guys,
    I want to move left/right when i am in zoom mode. But when i try it the application will go to next image. how should I handle it?

  • aiman

    You are, as always, a life saver. Thank you so much for your knowledge 😀

  • Alec

    Hello there! Is it possible to fetch images from a folder within the app?
    ex. “my app/res/photogallery/”
    thank you in andvance!

    • MHT

      create a subdirectory of your assets folder called “clipart” and try this code.

      protected void onCreate() {
      blah blah..
      File clipartdir = new File(basepath + “/clipart/”);
      if (!clipartdir.exists()) {
      clipartdir.mkdirs();
      copyClipart();
      }
      blah blah
      }
      private void copyClipart() {
      AssetManager assetManager = getResources().getAssets();
      String[] files = null;
      try {
      files = assetManager.list(“clipart”);
      } catch (Exception e) {
      Log.e(“read clipart ERROR”, e.toString());
      e.printStackTrace();
      }
      for(int i=0; i<files.length; i++) {
      InputStream in = null;
      OutputStream out = null;
      try {
      in = assetManager.open("clipart/" + files[i]);
      out = new FileOutputStream(basepath + "/clipart/" + files[i]);
      copyFile(in, out);
      in.close();
      in = null;
      out.flush();
      out.close();
      out = null;
      } catch(Exception e) {
      Log.e("copy clipart ERROR", e.toString());
      e.printStackTrace();
      }
      }
      }
      private void copyFile(InputStream in, OutputStream out) throws IOException {
      byte[] buffer = new byte[1024];
      int read;
      while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
      }
      }

      • Axay Prajapati

        can you set it properly ?

      • MHT can you show how you make this on this tutorial please? Thank you

  • Ghanshyam Gupta

    hi my problem is when i click on first image of gridview it didn’t respond but for other it work fine
    and when i put small density images in grid view it work for every position including first position
    please help me

    • soft xm

      Me too help me , please !

  • Ghanshyam Gupta

    your image gallery is not working with images taken from camera solve this problem

  • Guest

    ha ha i found my self -first thing ravi you use onitemclickListener to open image in full screen
    i use onitemclicklistener on gridview and pass position so now it work fine
    second for fullscreen adapter you didn’t apply decodefile method when set image on full screen it cause out of memory problem

  • Ghanshyam Gupta

    ha ha i found my self -first thing ravi you use onclickListener to open image in full screen
    i use onitemclicklistener on gridview and pass position so now it work fine
    second for fullscreen adapter you didn’t apply decodefile method when set image on full screen it cause out of memory problem

    • Sereen Shalby

      can you fix the out of memory problem?

  • nokiajavi

    Thanks for this magnific tutorial, but whrere is the class FullScreenViewActivity.java ??? The download LINK don’t work. Thanks you!

  • no name for u

    ah come on !!! fullscreenview where is it ? also please change your website stile.. NOT EASY TO FIND AN ARTICLE !!!! useless design !!

  • Hossam Alaa

    Thanks for this article!

    To avoid the java.lang.OutOfMemoryError exception for large images the solution is pretty simple.
    just remove ARGB_8888, and use RGB_565 instead (in FullScreenImageAdapter class)

    • Eriza Ardi

      I’ve tried your solution about using RGB_565. But, when I tap any image there’s message like this..
      “Bitmap too large to be uploaded into a texture (2592×1944, max=2048×2048)”

      And the image doesn’t show. Just blank page with button close at the top right corner. Any idea?

  • Mike

    nice work I have a problem though. When I zoom the ImageView and try to navigate it(reach the bounds of the image) the viewPager is scrolled instead. Do you know how can I pan the image until I reach the bounds and the swipe the viewPager?

  • Tugsbayar

    I have a problem with NAT directory..
    Error message is “Directory path is not valid!” Please set the image directory name AppConstant.java class.
    How to solve it ?

    • Eriza Ardi

      Please create folder in sdcard directory named “NAT”, the fill it with some images. After that, relaunch the app.

      • Afras

        How can I do this? Thank you…

  • Ramya P

    hi, can you pls tell me
    i dont want to use sd card i need to put images directly, what can i do for that?

  • Guest

    hi tnx for your tutorial one question how can i get the image which is shown?i want to make it as wallpaper or share it

  • Simon Astbury

    Hi Ravi,
    I’ve been a developer for many years but only about a year with Java and I have to say this tutorial is absolutely brilliant. Not only for its functionality but it’s given me real insight into how a project should be properly designed to implement MVC. Truly staggering!
    Thank you.

  • deni777

    Hello.Very ,very nice tutorial!!!I want to ask something i want to add option -Set wallpaper on Full screen image.How to do that?Help me please.

    • kamran

      WallpaperManager wm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);

      Bitmap myBitmap = BitmapFactory.decodeFile(_imagePaths

      .get(position));

      DisplayMetrics displayMetrics = new DisplayMetrics();

      getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

      int height = displayMetrics.heightPixels;

      int width = displayMetrics.widthPixels;

      myBitmap = Bitmap.createScaledBitmap(myBitmap, width, height, true);

      try {

      wm.setBitmap(myBitmap);

      wm.suggestDesiredDimensions(width, height);

      } catch (Exception e) {

      // TODO Auto-generated catch block

      e.printStackTrace();

      }

      also add permissions

  • rahul

    hello…my grid is getting displayed with the images..but on clicking any image..it gives d dialog box with the message that the app has stopped working..please help…

    • Ghulam Mohammed Taher

      you might be adding large size images try to reduce the image pixels it will work. If the pixel density is large then the application throws outofmemoryexception and abruptly stops the application

  • vahid

    tank you very much.

  • kamran

    hi ravi ,a big question
    how can we improve the gridview performance?

  • Ramya P

    hi ravi, your tutorial is very helpful to me, in this program i want to add the images in program directly, can you pls tell me how to write the code?

  • Rabin Shrestha

    @ravi8x:disqus Using your FullScreenImageAdapter.java I managed to make a slider. And what I did is added two things 1. spinner and 2. TextView. I want those two in each image and ya they are there.Now I made a button that submits all these to an api. But the problem is how can I get the value of all the spinners and textviews. I just get a Spinner and textviews value.. Please Help ASAP.. 🙂

  • kamran

    why some images keep repeating in the gridview it drives me crazy i cant understand it!

  • Hi, your source is really helpful for me, but now I’ve got a question.

    I zoom an image and after that, I don’t want to slide to the next pager until I get to the edge of the image. Has someone a idea, where I can check, if I’m at the egde of an image?

    • MUHAMMAD ALI

      @mars3142:disqus, did u find any solution for this problem…i was also wondering to control that issue.

  • James Carter

    A few simple edits this is now pulling images from a feed and utilizing android query for easy caching.

    Awesome tutorial, thanks 🙂

  • max4ever

    thanks a lot

  • christine

    Thanks for your article. Its very helpful for my final project. I will ask how to load image from drawable or web sevice ? Thanks before

  • swarna

    Where is FullScreenViewActivity.class in this article….?

  • erum hannan

    can someone please help me i am getting image names from database each time either 2 or 3 images if images are greater than one then it should not enable paging otherwise it should enable paging how can i load different images in this method:
    public Object instantiateItem(ViewGroup container, int position) { }
    i am not getting how to load images and and for each image i have used touchImageview zoomin and zoomout buttons controls that is working fine but i am failed to include paging part with touchImageView

  • Savio Palmieri

    Sorry I tried to execute this tutorial on my device, but the Full Screen Activity is viewed only if I standby my device … In Debug mode with a breakpoint in the OnImageClickListener in the GridViewImageAdapter class it never executes the Intent… if i try to launch a Toast it doens’t appear…. Thanks for help…

    • gdguradio@gmail.com

      sir i am also trying to do this tutorial may i ask did you download the code or just copy paste it i havent started it so if it is not working might as well not try it thank you

      • Savio Palmieri

        I copied the example code in my project and I also created a new project by the code downloaded. The problem is the same….

        • gdguradio@gmail.com

          any progress on the project sir?

          • Savio Palmieri

            Nothing … 🙁

    • Miguel Lozano

      i have same problem, if i click in the first image ,this dont execute OnImageClickListener, if i move grid , yes execute onClick. When I click other image, work fine. what happens?

    • Savio Palmieri

      [SOLVED] about the OnClick listener set the FullScreen login in the grid view’s setOnItemClickListener method (gridView.setOnItemClickListener(new GridListener())) and not into the single view into the adapter 😉 it works now 😉

  • UB

    Can someone help me please.
    I want to use an image with an icon inside to be scaled both.
    I’ve tried something like this:

    but I am getting this error ‘Exception raised during rendering: info.androidhive.imageslider.helper.TouchImageView cannot be cast to android.view.ViewGroup’.

    Thanks in advance

  • ishengo

    the application starts but fails to display full screen.

  • Michael

    Hi, i cant find the FullScreenViewActivity.class
    and the download doesnt work right now.. need help please!

  • eddy

    Thanks for the touchImageView stuff

  • Tf

    Thanks for the tutorial.It is very useful.
    I would like to know how can I implement the slideshow function(i.e. auto slide).

    Should I edit FullScreenImageAdapter.java?Would you mind providing me some sample code?
    It will be a great help for me if you would like to take some time to help me out.
    Thanks a lot!

  • Gops AB

    I can’t able to download the code. I have given my mail id . but i dint get any mails.

    • Gops AB

      What to do? please help me.

    • Check your spam folder once.

      • Gops AB

        I chekced there. No notifications yet

        • Gops AB

          Or else help me where is the class FULLSCREENVIEWACTIVITY

      • Michael

        There is no E-Mail
        tried it with three different e-mails

      • Manny264

        ive also not been able to download the code may you please email it to me at admin@omafano.com

  • vinil

    my photos are located in Internal Storages, Picture folder.. Please help me for this..

    what code has to change in

    File directory = new File(

    android.os.Environment.getExternalStorageDirectory()

    + File.separator + AppConstant.PHOTO_ALBUM);

  • Farouk Elabady

    Hello,

    For people asking for the missing class FullScreenViewActivity

    here is the sample I managed to create

    public class FullImageActivity extends Activity {

    private ArrayList imagePaths = new ArrayList();

    private Utils utils;

    private PagerAdapter mPagerAdapter;

    private ViewPager mPager;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.full_screen);

    // get intent data

    Intent i = getIntent();

    utils = new Utils(this);

    // loading all image paths from SD card

    imagePaths = utils.getFilePaths();

    // Selected image id

    int position = i.getExtras().getInt(“id”);

    mPagerAdapter = new FullScreenImageAdapter(this, imagePaths);

    mPager = (ViewPager) findViewById(R.id.pager);

    mPager.setAdapter(mPagerAdapter);

    mPager.setCurrentItem(i.getExtras().getInt(“position”));

    // ImageView imageView = (ImageView) findViewById(R.id.imgDisplay);

    // imageView.setImageResource(imageAdapter.mThumbIds[position]);

    }

    }

  • Hi, thanks for your good tutorial.
    there is one problem, when I zoom image (almost when there is just 1 image) and try to pan just in horizontal direction, image will move so slow and disconnects from moving. but if I try to pan horizontal and vertical (for example from bottom left to top right) there is no problem. also there is no problem in vertical panning

  • Julio Coimbra

    Thanks, very good tutorial!

    But instead of getting the images from a sdcard

    File directory = new File(android.os.Environment.getExternalStorageDirectory()

    + File.separator + AppConstant.PHOTO_ALBUM);

    i am trying to get the the images from, for example, the drawable folder.

    File directory = new File(“/FullScreenImageSlider/res/drawable”);

    It is not working. Once i run the application i get the following error.

    NAT directory..
    Error message is “Directory path is not valid!” Please set the image directory name AppConstant.java class.

    Can someone help me?

    Thank you.

    • Ihor Pysmennyi

      You can get the drawable this way:

      Resources resources=context.getResources();
      Drawable drawable=resources.getDrawable(R.drawable.vsd_320);

  • Joseph Dalebert Cajida

    sir i need some help.. when i run the program..

    there is always an error saying that the “folder” directory path is not valid! Please set the image directory name AppConstant.java class

    i dont know how to fix it.

    • I have the same problem. But when I insert images to the folder in SDcard my app crashes after click on the Photos link.

    • Archana Sarang

      hi, Joseph. Create a new folder in the sdcard named “album” and put some images in it. And set this value aka “album” to PHOTO_ALBUM in AppCnstant.java file. Dnt forget to set the permission in app’s manifest file.

      • Joseph Dalebert Cajida

        i did try that but still it cannot find the directory of the PHOTO_ALBUM.

        • Archana Sarang

          In the AppConstant.java file you have declare a variable ,

          Here PHOTO_ALBUM’s String value is “album”…

          ‘ public static final String PHOTO_ALBUM=”album”; ‘ Right ?

          This “album” is the name of the folder that you must have created inside your phone’s sdcard… (“sdcard/album”), then put some images to it, set the permission in the android project’s menifest file : ” ”

          Then try to run your app…

  • This tutorial using Environment.getExternalStorageDirectory() isn’t a good choice because some versions of Android dont find the mnt/sdcard…

  • Thanks for tutorial but i want to get images from my app res/drawable folder or from internet how can i do this?

  • John

    Great project Ravi, thank you. Does anybody know how could I show the image_file_name under each small image in the grid?? it would be so useful. I have deployed the code in eclipse but I don’t know exactly what class I should modify. Any help??

    Thank you

  • tuhin khan

    Hi Ravi, its a great tutorial but I want to make some modification. Like I don’t want to show gridView but it will direct display image full screen and rest of them r fine !
    if you please suggest me, how can I do that?

  • Dilip Kumar

    Thank you very much it help me lot .. i implemented rotation also in this project but it is not rotationg in center of the screen .. can u please help me

  • shoaib

    where is FullScreenViewActivity???????????????????

    • ofi

      where is?

  • Lottie

    Is there a way to translate this to find the internal storage pictures?

  • waseem ahmad

    Ravi ..How to Slide Item On click

  • bobo

    There is a big problem , when I have a lot of images in the folder and I scroll down .. it’s not smooth and so slow

    is there a way to make it better when scrolling down ?

  • Venkat

    Hi Ravi. This code was really helpful. Thanks a lot. I have 1 doubt. When i zoom into an image and in the same state if i try to swipe through it, the next image is getting loaded and when i come back to same image, it will be in zoomed in state. Is there anyway to stop loading next image when it is in zoomed in state.?

    • ikken

      Hi venkat, this heppens because of the ViewPager actually intercepts the touch event first. the solution is to extend the ViewPager so that the new inherited class could disable touch events handling when the image is zoomed out. here my code

      public class MyViewPager extends ViewPager{

      private boolean swiftEnabled = true;
      public MyViewPager(Context context) {
      super(context);
      }

      public MyViewPager(Context context, AttributeSet attrs) {
      super(context, attrs);
      // TODO Auto-generated constructor stub
      }

      @Override
      public boolean onTouchEvent(MotionEvent event) {
      if (this.swiftEnabled) {
      return super.onTouchEvent(event);
      }

      return false;
      }

      @Override
      public boolean onInterceptTouchEvent(MotionEvent event) {
      if (this.swiftEnabled) {
      return super.onInterceptTouchEvent(event);
      }

      return false;
      }

      public void setSwiftEnabled(boolean enabled){
      this.swiftEnabled = enabled;
      }

      • guest

        where do i add this piece of code??

      • apperstand

        doesn’t work at all.
        if swiftenabled is set to true – zoom is disabled
        if swiftenabled is set to false – does exactly the same as with default viewpager

  • Jonathon Trainor

    Hi Ravi. Thanks for the tutorial! It has really helped me a bunch. I was wondering if there was anyway that AppConstant.PHOTO_ALBUM could be changed dynamically depending on which activity opened the gallery, so that each activity could view the specific photos belonging to them. I have tried a lot of different things but can’t seem to get this accomplished. Any help on this would be greatly appreciated.

    Thank Again.

  • Guest

    10-15 11:16:58.261: E/AndroidRuntime(25564): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.imageslider/info.androidhive.imageslider.GridViewActivity}: java.lang.NullPointerException

    why this happen to me?

    • Guest

      stop after this code :

      imagePaths = utils.getFilePaths();

      i created NAT folder in /storage/emulated/0/ and put images in NAT folder..
      Please help,
      Thank you

      • Guest

        i think i got error from this code :
        listFiles.length
        (class : Utils.java, function : getFilePaths())

        anyone can help me to fix this error?
        listFiles.length cannot count all files in my folder.
        File[] listFiles = directory.listFiles(); => this code return null;

        PLEASE HELP

        • Guest

          solved:
          forget this

  • Alireza saemi

    unfortunately when importing with gradle and andriod studio its is not going to work . its says NAT directory pass is not valid ! please set image directory name app.constant.java ..

    i tried it with eclipse with no success . im using downloaded project

    • Alireza saemi

      @Archana Sarang thank u so much … i set permission . permission should declare as child of manifest … a tag that is above application tag .. now errors gone .. it says your album is empty 🙂 … i load some images but i guess i should restart emulator .

      • Alireza saemi

        Awesome
        Awesome .. Hey developers if u want to import on gradle and studio first edit app with adt and then import it . eevery thing will be alright . thank u so much man for awesome code

  • zozo

    Hi I have some performance issues. When I click on image grid (first on left top) FullScreenImage doesn’t bring up immediatly. I must click on screen for bring up FullScreenImage. When this FullScreenImage bring up the button “close” doesn’t close it. I must click several times on button “close” to close it.
    How can I fix it ?

    thanks

    • Iván

      +1, please somebody have a solution to fix this error??

    • nirosha

      hiii i have multiple images are do pinch zoom and rotation
      images are get in to gallery not drawable
      plz help me

  • Rohit

    When I click on image i get the error “unfortunately fullscreenimageslider stop work”Help ma plzzz

  • Alexander
  • phanit

    I was looking for Pinch Zoom function of ImageView in ViewPager. And your function works quite well. Thank you so much!

  • Arjun Narahari

    hello this is arjun narahari , i am posting a doubt which i had posted in stackoverflow and in fb also but never got a proper reply , i m hoping that i could get a better solution according to my program , most of my program are from above codes but i have implemented a horizontal scrollview on the viewpager page , i am actually a little bit offtopic here , i hope someone could help me

    http://stackoverflow.com/questions/27040736/how-to-set-images-from-horizontal-scrollview-into-the-viewpager-in-android/27041215#27041215

  • Ivan Santiago

    Hi I have some performance issues. When I click on image grid (first on left top) FullScreenImage doesn’t bring up immediatly. I must click on screen for bring up FullScreenImage. When this FullScreenImage bring up the button “close” doesn’t close it. I must click several times on button “close” to close it.
    How can I fix it ?

  • Francesco

    Hi! When i Can find your images? i love the pic with the hug between that couple *_*

  • Anak Timor Leste

    How I can implemented pinch zoom with flip image

  • Niusha Karimi

    How Can I Choose Another Directory To Load Images? (not SD Card)
    e.g : drawable or assets

    Plz Help Me
    I Tried Lots of Way :(((

  • Sai Nalla

    HI Ravi bro
    I love this example but i want to access the images from drawable folder
    howw

  • Sagar Maiyad

    Hi Ravi, i want to drag image with my crop area. how can i acheive using your custom imageview.?

  • snake223

    How I can imrpoove TouchImageView to zoom image by double tap? please help me

  • smithy

    I have a problem with the Files Directory:

    public static final String PHOTO_ALBUM = HERE I WANT MY DRAWABLE FOLDER

    what i have to do, to set the drawable folder? I want to deliver the pictures with the app which are in my drawable folder.

    could some one help me?

    I already tried some thing like that:

    public static final String PHOTO_ALBUM = Resources resources=context.getResources();

    Drawable drawable=resources.getDrawable(R.drawable.vsd_320);

    but dont work

    • musethoplicious 3rd

      i had same question of this. please help

  • Likith

    How to add a delete button to image view . So that when image is deleted , image gets deleted in the gallery and grid view as well.

  • akkus

    nice tutorial.. but i havnt seen fullscreenview activity.. i cant download ur code bcz unsuscribed.. confirmation email not reached..

  • Никита Чурилов

    It’s a Great Tutorial. Big Thanks to Ravi!

  • droidman

    HOW show no Pictures form SD Card, i want to show DRAWABLE Pictures. I have no idea to do this!
    Or how can i do this, i only want de deliver some pictures to the users, which they can see in this “Gallery”. Thanks for your HELP!

  • Anderson Bressane

    Thanks!!! 😀

  • Aya M Salama

    Ravi, I get your error message ” directory path is not valid! Please set the image directory name AppConstant.java class”,, even when i downloaded your sample
    I’am a little bit confused about where are you storing images, or you’re just getting them from a folder in the device

    If you can give me any hint about the best way to display large amount high resolution images

    Thanks for your efforts

    • Aya M Salama

      ouch, does that mean i need to change the “android” thing with a directory to the images or what?

    • pavan

      go to app constant and change the path to a directory thats already defined in your gallery or file manager. eg- public static final String PHOTO_ALBUM = “Pictures”;

      best way to display high res images- GridViewImageAdapter.java-> Bitmap decodeFile-> 02.inSampleSize, change it from “scale”to multiples of 2 or 4. 2 works fine for me.

  • Anil Eger

    Double Tap zoom should be in that tutorial….

  • Hareesh

    Add the following two permissions if at all you get “directory path is not valid!” error.

  • adavan

    nice tutorial…..

  • FullScreenViewActivity is MISSING, Maybe Ravi forgot to put.

    Here it is. http://pastebin.com/AE43gG27

    • chha

      ya ravi forgot to put it and which put me in troble thank u so much shifar.. 🙂

      • Pls find it in downloaded source code. I’ll add the code for it.

        • chha

          thank u for your support 🙂 and i just want to say i love your all
          tutorials,as I’m new in android it’s pretty much helpful for me to
          understand android.. & i believe it works for others too.. my love for android– credit goes to your tutorials.. plz share more and more.. <3 🙂

      • welcome mate.

  • saish neugi

    How can i load the images from urls fetched from json instead of directory

    • saish neugi

      Does anyone replies here? I am still struck with this . .

  • musethoplicious 3rd

    hi ravi, nat directory path is not valid in the appconstant.java, please help me everyone

  • David Rönn Jansson

    Hi Ravi!
    Thank you for a great article and guide!

    About the last part where you’re writing “I know this project has some performance issues like grid scrolling is little bit slow. Search and try to find a solution to make it better.”

    Do you know why this is occurring? Do you know where I can find “a better solution”?
    I appreciate the help, either from you of from anyone else!

    Best – David

  • pankaj talaviya

    NAT directory path is not valid!
    Please set the image directory
    name AppConstant.java class

    • harin kaklotar

      public static final String PHOTO_ALBUM = “[here your image folder path]”;
      example
      public static final String PHOTO_ALBUM = “Download”;
      here Download is your image folder path of SdCard.

  • Ambreen Khan

    Sir,I am using Listview from one of your listview tutorial, I want to download images from URL,I succeed and I can see and load image in single item view activity, But how can I use to slid Image from left to Right or Right to left?? My code is bellow

    import java.io.InputStream;
    import java.lang.reflect.Array;
    import java.net.URL;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.Toast;

    public class SingleItemView1 extends Activity {

    TouchImageView img;
    Bitmap bitmap;
    ProgressDialog pDialog;
    String name;
    private ImageLoader imgLoader;
    int position;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.singleitemview1);

    Intent i = getIntent();
    // Get the name
    name = i.getStringExtra(“Nurl”);
    // position = i.getExtras().getInt(“id”);
    // System.out.println(name+position);
    // Log.d(“Tag Name”, position + name);

    img = (TouchImageView)findViewById(R.id.imge);
    imgLoader = new ImageLoader(this);
    imgLoader.DisplayImage(name, img);
    new LoadImage().execute(name);
    }

    private class LoadImage extends AsyncTask {

    @Override

    protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(SingleItemView1.this);
    pDialog.setMessage(“Loading Image ….”);
    pDialog.show();

    }

    protected Bitmap doInBackground(String… args) {

    try {

    bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());

    } catch (Exception e) {

    e.printStackTrace();

    }

    return bitmap;

    }

    protected void onPostExecute(Bitmap image) {

    if(image != null){
    img.setImageBitmap(image);
    pDialog.dismiss();
    ‘}else{

    pDialog.dismiss();
    Toast.makeText(SingleItemView1.this, “Image Does Not exist or Network Error”, Toast.LENGTH_SHORT).show();
    }
    }
    }
    }

    I am getting Position and URL from previous Activity successfully but I dont know how to slid next image Please Help.

  • Azhar Awang

    Thank you for this codes. I tried modifying so that it can be implemented with Notepad, where a user can write notes, and view an album he chooses.

    In GridViewActivity:

    String foldername =”@@@@”; //to be obtained from EditText getText toString
    File directory = new File(

    android.os.Environment.getExternalStorageDirectory()

    + File.separator + foldername);

    In GridViewImageAdapter:

    i.putExtra(“Useralbum”, _filePaths ); // pass to Full Screen

    In FullScreenView:
    String foldername = i.getStringExtra(“Useralbum”);

    //
    File directory= new File ( ……………… + File.separator + foldername);

    Codes with no error, and exported APK and installed.

    Final result is either blank screen, or it displays all images in sdcard/ , not the chosen foldername.

    If this can be solved, I believe we have very good codes similiar to Android 3Q Photo Album with 10 million users.

  • Mrko Both

    I found the solution to issue Ivan Santiago:
    “Hi I have some performance issues. When I click on image grid (first on left top) FullScreenImage doesn’t bring up immediatly. I must click on screen for bring up FullScreenImage.

    How can I fix it ?”

    First:
    In your class: GridViewActivity, change the parameters that you send:

    // Gridview adapter
    adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths, columnWidth);

    to:

    // Gridview adapter
    adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths, columnWidth, gridView);

    gridView is the variable that I use to my GridView element.

    Then change the constructor on GridViewImageAdapter.class

    public GridViewImageAdapter(Activity activity, ArrayList filePaths,
    int imageWidth, GridView imageCarrete) {
    this.activity = activity;
    this.filePaths = filePaths;
    this.imageWidth = imageWidth;
    this.imageCarrete = imageCarrete;
    }
    dont forget declare: private GridView imageCarrete;

    Finally, create the event in the method getView(), in the same class GridViewImageAdapter.class

    // Listener del GridView
    imageCarrete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
    Intent i = new Intent(activity, FullScreenViewActivity.class);
    i.putExtra(“position”, position);
    activity.startActivity(i);
    }
    });

    And detele imageView.setOnClickListener(new OnImageClickListener(position)); the class too…

    class OnImageClickListener implements OnClickListener {

    int _postion;

    // constructor
    public OnImageClickListener(int position) {
    this._postion = position;
    }

    @Override
    public void onClick(View v) {
    // on selecting grid view image
    // launch full screen activity
    Intent i = new Intent(_activity, FullScreenViewActivity.class);
    i.putExtra(“position”, _postion);
    _activity.startActivity(i);
    }

    }

  • Ansari Sufiyan

    Ho do i use swipe view with drawable image instead of sd card

  • hardik

    i downloaded your source code but i get one error while i am running error is NAT directory path is not valid! please set image directory name AppConstant.java class how to fix it??

    • harin kaklotar

      public static final String PHOTO_ALBUM = “[here your image folder path]”;
      example
      public static final String PHOTO_ALBUM = “Download”;
      here Download is your image folder path of SdCard

      • ahmad

        please help me where can i found this folder in the emulator ??

        • harin kaklotar

          String ExternalStorageDirectoryPath =Environment.getExternalStorageDirectory().getAbsolutePath();

          this is your sdcard path in emulater and in sdcard Download folder

          public static final String PHOTO_ALBUM = ExternalStorageDirectoryPath + “Download”;

          here Download is your folder

  • Omali

    Hey does anyone know where I can find the package in the second step of the

    “Creating new project” section?

  • nadika

    public static final String PHOTO_ALBUM = “?????????”;

    • harin kaklotar

      your image folder path

  • Vasim Kadri

    Hello Ravi sir can you help me out?

    I am using below code for setting my View pager scrollview using url’s String array and also using UIL for image Loading.

    imageLoader = ImageLoader.getInstance();

    options = new DisplayImageOptions.Builder()

    .showImageForEmptyUri(R.drawable.ic_launcher).cacheOnDisc()

    .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();

    pager = (ViewPager) findViewById(R.id.pager);

    pager.setAdapter(new ImagePagerAdapter(strings));// strings is string[]

    listener = new DetailOnPageChangeListener();

    pager.setOnPageChangeListener(listener);

    ————————————————–****——————-
    Now I want to zoom the current image of viewpager.
    what is the solution for this??

  • Taksh

    You forgot to give permissions in manifest.

  • Biz

    amazing info! many thanks for sharing!

  • Emmanuel Arzate

    FullScreenViewActivity is missing on page. I have tried to download the code sample but I can’t without logging in. I tried to register but Android Hive has not sent me an email confirming my registration….

    • Xu Justin

      you can also log in with Facebook, I didn’t receive the email but it works when I login in with Facebook

  • harin kaklotar

    why download button not work in your website?

  • Hrishav Raj

    Can any1 help me out with this??????

    FullScreenViewActivity cannot be resolved to a type

    GridViewImageAdapter.java

    /info.androidhive.imageslider/src/info/androidhive/imageslider/adapter

  • Andrius Jurgelevičius

    Can someone help me how to rewrite this code to load images not from the phone but from the app? Big thanks for help!

  • R.Ritesh

    I’m not able to zoom image by using above same code.

    private int[] GalImages = new int[] { R.drawable.one, R.drawable.two,
    R.drawable.three };

    touchImageView.setImageResource(GalImages[position]);

    ((ViewPager) container).addView(view, 0);

  • Soha Gamal

    http://stackoverflow.com/quest
    plz any one can help me in this question about viewpager here

  • Hai.. Thank you very much for this post. It helped me a lot..

    but you forgot to add these permission in manifest if download code and import in eclipse:

    >

    • Anand AnGryboyzz

      Dude Thk you so much your answer saved my time 🙂

    • Kh Fasi

      I have added permission in the manifest but still i am facing null error

  • Gaurav Meghanathi

    when user click on grid-view particular item that item id (database id) send to full screen activity and i get that id intent through but when i set that id into pager then pager always show the next id , otherwise that id set into image view perfectly run i was unable to find . that kind of solution so anyone can help me please…

  • Kamran Hussain

    what if i want to use a folder from a server instead of SDCard ??

    File directory = new File(

    android.os.Environment.getExternalStorageDirectory()

    + File.separator + AppConstant.PHOTO_ALBUM);

  • sunil zaware

    Thanks Guys,

  • Milan gajera

    hey guys i got error on GridViewActivity.java error like this

    gridView.setNumColumns(3);

    above line forced close my app and i got error like below

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.GridView.setNumColumns(int)’ on a null object reference

    at com.domore.gridviewtutorial.AndroidGridLayoutActivity.InitilizeGridLayout(AndroidGridLayoutActivity.java:46)

    at com.domore.gridviewtutorial.AndroidGridLayoutActivity.onCreate(AndroidGridLayoutActivity.java:34)

  • Michelle tbs

    Hi , i was not able to get the picture event though I have replace with the correct path

    aused by: java.lang.NullPointerException: Attempt to get length of null array

    at info.androidhive.imageslider.helper.Utils.getFilePaths(Utils.java:39)

    at info.androidhive.imageslider.GridViewActivity.onCreate(GridViewActivity.java:36)

    at android.app.Activity.performCreate(Activity.java:5975)

    • Archis Thakkar

      Same problem i am facing please Suggest

    • Kh Fasi

      Facing same issue

  • osiris rodriguez

    /* If you dont want to use your sd card and only your drawable, just modified this code in your FullScreenImageAdapter.java (note: you not gonna use any more your utils.java) */

    package com.android.app.catalogosrd;

    import android.app.Activity;
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.Drawable;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.RelativeLayout;

    public class FullScreenImageAdapter extends PagerAdapter {

    private Activity _activity;
    private String _imagePaths;
    private LayoutInflater inflater;

    //the images to display
    Integer[] imageIDs = {
    R.drawable.ic_1,
    R.drawable.ic_2
    };

    // constructor
    public FullScreenImageAdapter(Activity activity,
    String imagePaths) {
    this._activity = activity;
    this._imagePaths = imagePaths;
    }

    @Override
    public int getCount() {
    // return this._imagePaths.size();
    return Integer.parseInt(String.valueOf(imageIDs.length));
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
    ImageView imgDisplay;
    Button btnClose;

    inflater = (LayoutInflater) _activity
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
    false);

    Resources resources = this._activity.getResources();
    Drawable drawable = resources.getDrawable(R.drawable.ic_1);

    imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);
    imgDisplay.setImageResource(imageIDs[position]);
    btnClose = (Button) viewLayout.findViewById(R.id.btnClose);

    BitmapFactory.Options options = new BitmapFactory.Options();
    // options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    // Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);

    //imgDisplay.setImageBitmap(bitmap);

    // close button click event
    btnClose.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    _activity.finish();
    }
    });

    ((ViewPager) container).addView(viewLayout);

    return viewLayout;
    }

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

    }
    }

    • W Fabiian Rojas

      But you’re just changing the FullScreenView view. it would be like to see my drawable images in GridView and coding GridViewImageAdaptador

      • osiris rodriguez

        change this var in Gridviewactivity.java

        // loading all image paths from SD card

        imagePaths = utils.getFilePaths();

        with this

        //the images to display
        Integer[] imageIDs = {
        R.drawable.ic_1,
        R.drawable.ic_2
        };

        imagePaths = imageIDs[position];

        • W Fabiian Rojas

          Amigo no te logro entender, y me das codigo incompleto.
          Ojala me puedas ayudar, soy de Colombia.

          • osiris rodriguez

            Agregame a Hangout (por gmail) para ayudarte mejor. rafaelosiris@gm***.com.

            Saludos

        • Tejpalsingh Siledar

          What is position??

    • Emmanuel Taah

      I have tried replacing the FullscreenImageAdapter with that code
      but its not still working, can you help me

  • chirag

    which path set on photo ablum in util.java class

  • Gamis

    Hey Ravi… you forget put the FullScreenViewActivity Activity in this example… haha.. well Thank you for the tutorial !!!

    • Yeah, but you can find the code in downloaded project.

      • Simple User

        your post isn’t here to help others but to have more subscriber… so bad, I’ll not follow you anymore. => Blacklist site

  • Ammar

    Heyy, I want to convert these activities into fragments but the fullscreen view doesn’t work. Help please

  • Hope so this code works with eclipse too.

  • Prakash Rai

    grid view scroll is very slow please solve it

    • Ashish Mathur

      use Glide rather than bitmap.. its very smooth

  • Ichwanul Muslim Al-Kalibatani

    ravi, there is no file in download menu

  • Shafqat Mehmood

    sir, can i use this above download file as my android project ? if yes. How can is this possible. actually I want to run as this in my software android studio. guid me please

  • how can use my computer pic in this project. I want to use personal images.

  • pavan

    You save a lot of our time! thank you 🙂
    i can now directly work on removing an item with long press.

  • Emmanuel Taah

    Can some one really help me
    I Want images to be display from Drawable

  • Jack

    Thanks Ravi for sharing this code! It’s easy to follow. Moreover, we have developed a new unique transition between slides: https://github.com/Cleveroad/Bitutorial. Could you give your opinion, please?

  • Archis Thakkar

    Help me out please Ravi I am getting Null Pointer Exception when I am Providing path to PHOTO_ALBUM as “Download”.Please Suggest Something

    • Kaunis

      Don’t forget to set
      in your AndroidManifest.xml.

      • Kh Fasi

        I am facing same issue, though i have added permission in my manifest but still i am getting this error
        Kindly reply

  • Eswar

    Is there any way to show all images from entire phone rather than specifying a folder name?

  • Kaunis

    I want to display on a unique window, the grid with images and the selected image on a separate window same screen.
    How can I do to display that image without clearing the entire screen ? Thanks.

  • parves suzon

    How do I use internal storage path?
    Can I use drawable image instead of storage image in slider?

  • bhupathi

    How do I use internal storage path?

  • bhupathi

    how to use use drawable image instead of storage image in slider? or get drawable folder path for the image..

  • Deepak Tomar

    Hi,

    I got error below error in this app, i am new in android development please help

    java.lang.OutOfMemoryError: Failed to allocate a 21233676 byte allocation with 2097056 free bytes and 4MB until OOM

    • Dhruv Nirmal

      you can add in your manifest file on
      android:hardwareAccelerated=”false”
      android:largeHeap=”true”

  • Pierre Abreu

    Thanks a lot for your tutorial!! 🙂 This code fits like a magic in my project and saved me a lot of time! You deserve a donation 😉 Regards

  • Fug

    Object does not always extend relative layout. You shouldn’t try casting it like that.

  • vikas kumar

    hi Ravi thanks for this code, i just implemented this in my project, and want to suggest if some one wants to test this on emulator like Genymotion, just hold right mouse button and just drag up and down to zoom in and out.
    thanks again.

  • pankj khedekar

    but there is one problem..image remains in zoom state even after moving to the next image and returning back to it..and come back to normal state only when instantiateItem method called again to create the view.. how to solve it?

  • android

    Hello Ravi,
    Thanks for great tutorial, am using pinch to zoom on imageView in view pager, image view remain zoomed even after going to previous page. How can I bring imageView as it is when user go back?

  • taar1

    Thanks for this amazing tutorial. It helped me a lot for the slider gallery for my new app!

    • I am glad it helped.

      • Madhuri

        Hello , I am able to load images in Grid View, but when I select one image, the application stops.
        Can you guide me with any solution?

  • Madhuri

    Hello , I am able to load images in Grid View, but when I select one image, the application stops.
    It says “Unfortunately , ImageViewer has stopped error.

    • Check the LogCat for errors.

      • Madhuri

        I am getting no errors. I am just not able to select any images after Grid View

  • apperstand

    hi everyone! i didnt use the gridview at all i have some other library that deals with that so i only used the viewpager images scroll and zooming from this tutorial.
    however i had some problems:
    1)images from phone’s camera wont load, they are too big according to the logcat.
    2)logcat also mentions number of frames skipped too much work on main thread.
    3)when i zoom in its almost impossible to move horizontally across the same image. viewpager thinks you scroll to the next image.

    i managed to solve 1 and 2 problems by using Glide library. https://github.com/bumptech/glide
    its very simple to use and internally is very efficient. no logcat warnings at all.
    add to that a progress bar (with a framelayout) on top of the imageview/touchimageview and put it in a listener and u have a real nice ux even when the image takes some time to load.
    however i couldn’t solve that third problem not even with what some people suggested here 🙁

    here’s some sample code solving my first and second issues:

    my instantiateItem inside FullScreenImageAdapter class

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
    TouchImageView imgDisplay;
    // Button btnClose;
    inflater = (LayoutInflater) _activity
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
    false);
    imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
    final ProgressBar progbar = (ProgressBar) viewLayout.findViewById(R.id.progress);
    Glide.with(_activity)
    .load(_imagePaths.get(position))
    .asBitmap()
    .listener(new RequestListener() {
    @Override
    public boolean onException(Exception e, String model, Target target, boolean isFirstResource) {
    progbar.setVisibility(View.GONE);
    return false;
    }

    @Override
    public boolean onResourceReady(Bitmap resource, String model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {
    progbar.setVisibility(View.GONE);
    return false;
    }
    })
    .into(imgDisplay);
    ((ViewPager) container).addView(viewLayout);
    return viewLayout;
    }

    my layout_fullscreen_image:

    (in my project the play_btn will be shown if the file is a video)

  • eri cahyana

    how to i can save images in aplication to storage ?

  • miller

    Hye Sir Ravi,

    i already downloaded the code twice but the project files seems to be not as it should be… It only contains 3 java classes and no layout files at all.. is there anything wrong or the project file need to be setting on somewhere?

  • Mahendra Chouhan

    sir how can i fetch all image from sd card or from phone memory ….

  • hardik

    hii
    can i get image in drawable folder???

  • Shivam Paul

    hi, can you please tell me
    i dont want to use sd card i need to show images from drawble folder, what can i do for that?

  • Vishal Kumar

    Project code is not Downloadeable Ravi.. Please send me Full Source Code to my email: vishal34336@gmail.com

  • Victor

    Hi,
    When i click the first GRID the full image activity wont open. The others it open.
    Do you know why?
    I found this but i didnt understand.
    http://stackoverflow.com/questions/11778228/onclicklistener-not-working-for-first-item-in-gridview

    • Kh Fasi

      When i click any grid view image the full image activity is not opened

  • Julius Sharwane

    Having trouble downloading the code because I’m not receiving the verification email to subscribe. Please help.

    EDIT: got it to work. login with your facebook account for those that are still confused.

  • Kh Fasi

    I am unable to add `Full screen activity on manifest file`

  • Peter Phyo

    How to do for TouchImageView in this situation.

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView = images.get(position);
    container.addView(imageView);
    return imageView;
    }

  • Staunstrup

    How do I find the right path to the images to use in AppConstant?

    I have tried Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))

    which gives me this: /storage/emulated/0/Pictures

    But that not work (Error! just after startup). Furthermore, I would prefer to get the path to the DCIM directory on my Samsung S4

    • Dhruv Nirmal

      exchange
      public static final String PHOTO_ALBUM = “androidhive”;
      to
      public static final String PHOTO_ALBUM = “Your Photo gallery Album name”;

      and

      put

      in manifest file

      Note: PHTO_ALBUM album name is from your Internal storage

      • Athar Mos

        what you mean with internal storage ..I can’t find the name of my album

  • Mohammad UmAr

    There is an error in my code ….. Directory path is not valid , what i can do now ?

    • Athar Mos

      same problem here????
      could any one please tell us what the problem in the directory?

  • Mitra.Razaghi

    You are amazing
    thank u :))))))))))))))))))))))))

  • Priyanka

    excellent explianation… i tried to implement this in my project but the error will continously pops out is Ïnvalid directory name”i dont no how to set this error… it will be great help if anyone can sort it out

  • Bluetoro

    The more the images the recycler view gets laggy. Any fix on this

  • Bluetoro

    Sorry. I mean the grid view scrolling gets laggy even in a hi end device

  • Aali Shan

    how should i download code its not downloading

  • Aali Shan

    someone have the complete working code please send me at aalishan181@yahoo.com

  • Nivetha Sajeesh (Nive Sajee)

    i need this for android 2.3 version. I need immediately. please help

    • Why are you still targeting 2.3?

      • Nivetha Sajeesh (Nive Sajee)

        Actually my project is in final stage. I used android version 2.3 because i used firebase database. Firebase will support only the version of 2.3. please help me. i am struggling

  • Sujit Kashyap

    Where is the FullScreenViewActivity file in this tutorial?
    I’m not able to download the code please send an alternate link

  • Snehal Tembare

    I am unable to zoom image on double tap how can I handle it?

  • Kristina Kaiser

    @ravi8x:disqus What is the way to download the image from the fullscreen and/or share it to an intent?

    Please help me as an expert!

  • Maulik Togadiya

    whare is FullScreenViewActivity??

  • Rizky Ramansyah

    this project cannt running in my android studio, and where FullScreenViewActivity. pls fast response sir

  • faizyab abbasi

    import info.androidhive.glide.R;
    import info.androidhive.glide.adapter.GalleryAdapter;
    import info.androidhive.glide.app.AppController;
    import info.androidhive.glide.model.Image;
    These libraries does not work for me please help me