Tuesday 25 March 2014

Calculator demo

 You can download demo from : "http://www.codeproject.com/Articles/104931/Introduction-to-Android-development-TouchCalculato"

OR
==
1)Create java file KeypadAdapter.java
==========================
package com.pragmatouch.calculator;

import android.widget.*;
import android.content.*;
import android.view.*;
import android.view.View.OnClickListener;

public class KeypadAdapter extends BaseAdapter {
private Context mContext;

// Declare button click listener variable
private OnClickListener mOnButtonClick;

public KeypadAdapter(Context c) {
mContext = c;
}

// Method to set button click listener variable
public void setOnButtonClickListener(OnClickListener listener) {
mOnButtonClick = listener;
}

public int getCount() {
return mButtons.length;
}

public Object getItem(int position) {
return mButtons[position];
}

public long getItemId(int position) {
return 0;
}

// create a new ButtonView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
Button btn;
if (convertView == null) { // if it's not recycled, initialize some
// attributes

btn = new Button(mContext);
KeypadButton keypadButton = mButtons[position];

switch(keypadButton.mCategory)
{
case MEMORYBUFFER:
btn.setBackgroundResource(R.drawable.keypadmembuffer1);
break;
case CLEAR:
btn.setBackgroundResource(R.drawable.keypadclear1);
break;
case NUMBER:
btn.setBackgroundResource(R.drawable.keypad1);
break;
case OPERATOR:

btn.setBackgroundResource(R.drawable.keypadop1);
break;
case OTHER:
btn.setBackgroundResource(R.drawable.keypadother1);
break;
case RESULT:
btn.setBackgroundResource(R.drawable.keypadresult1);
break;
case DUMMY:
btn.setBackgroundResource(R.drawable.appvertical1);
break;
default:
btn.setBackgroundResource(R.drawable.keypad1);
break;
}
// Set OnClickListener of the button to mOnButtonClick
if(keypadButton != KeypadButton.DUMMY)
btn.setOnClickListener(mOnButtonClick);
else
btn.setClickable(false);
// Set CalculatorButton enumeration as tag of the button so that we
// will use this information from our main view to identify what to do
btn.setTag(keypadButton);
} else {
btn = (Button) convertView;
}

btn.setText(mButtons[position].getText());
return btn;
}

// Create and populate keypad buttons array with CalculatorButton enum
// values
private KeypadButton[] mButtons = { KeypadButton.MC, KeypadButton.MR,KeypadButton.MS, KeypadButton.M_ADD, KeypadButton.M_REMOVE,
KeypadButton.BACKSPACE, KeypadButton.CE, KeypadButton.C,KeypadButton.SIGN, KeypadButton.SQRT,
KeypadButton.SEVEN,KeypadButton.EIGHT, KeypadButton.NINE, KeypadButton.DIV,KeypadButton.PERCENT,
KeypadButton.FOUR, KeypadButton.FIVE,KeypadButton.SIX, KeypadButton.MULTIPLY, KeypadButton.RECIPROC,
KeypadButton.ONE, KeypadButton.TWO, KeypadButton.THREE,KeypadButton.MINUS, KeypadButton.DECIMAL_SEP,
KeypadButton.DUMMY, KeypadButton.ZERO,KeypadButton.DUMMY,KeypadButton.PLUS, KeypadButton.CALCULATE };

}
2)KeypadButton.java
===============
package com.pragmatouch.calculator;

public enum KeypadButton {
MC("MC",KeypadButtonCategory.MEMORYBUFFER)
, MR("MR",KeypadButtonCategory.MEMORYBUFFER)
, MS("MS",KeypadButtonCategory.MEMORYBUFFER)
, M_ADD("M+",KeypadButtonCategory.MEMORYBUFFER)
, M_REMOVE("M-",KeypadButtonCategory.MEMORYBUFFER)
, BACKSPACE("<-",KeypadButtonCategory.CLEAR)
, CE("CE",KeypadButtonCategory.CLEAR)
, C("C",KeypadButtonCategory.CLEAR)
, ZERO("0",KeypadButtonCategory.NUMBER)
, ONE("1",KeypadButtonCategory.NUMBER)
, TWO("2",KeypadButtonCategory.NUMBER)
, THREE("3",KeypadButtonCategory.NUMBER)
, FOUR("4",KeypadButtonCategory.NUMBER)
, FIVE("5",KeypadButtonCategory.NUMBER)
, SIX("6",KeypadButtonCategory.NUMBER)
, SEVEN("7",KeypadButtonCategory.NUMBER)
, EIGHT("8",KeypadButtonCategory.NUMBER)
, NINE("9",KeypadButtonCategory.NUMBER)
, PLUS(" + ",KeypadButtonCategory.OPERATOR)
, MINUS(" - ",KeypadButtonCategory.OPERATOR)
, MULTIPLY(" * ",KeypadButtonCategory.OPERATOR)
, DIV(" / ",KeypadButtonCategory.OPERATOR)
, RECIPROC("1/x",KeypadButtonCategory.OTHER)
, DECIMAL_SEP(",",KeypadButtonCategory.OTHER)
, SIGN("±",KeypadButtonCategory.OTHER)
, SQRT("SQRT",KeypadButtonCategory.OTHER)
, PERCENT("%",KeypadButtonCategory.OTHER)
, CALCULATE("=",KeypadButtonCategory.RESULT)
, DUMMY("",KeypadButtonCategory.DUMMY);

CharSequence mText; // Display Text
KeypadButtonCategory mCategory;
KeypadButton(CharSequence text,KeypadButtonCategory category) {
mText = text;
mCategory = category;
}

public CharSequence getText() {
return mText;
}
}
3)Create java file KeypadButtonCategory.java
================================
package com.pragmatouch.calculator;

public enum KeypadButtonCategory {
MEMORYBUFFER
, NUMBER
, OPERATOR
, DUMMY
, CLEAR
, RESULT
, OTHER
}
4) create java file main.java
==================
package com.pragmatouch.calculator;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;

import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.View;
import android.view.View.OnClickListener;

public class main extends Activity {
GridView mKeypadGrid;
TextView userInputText;
TextView memoryStatText;

Stack<String> mInputStack;
Stack<String> mOperationStack;

KeypadAdapter mKeypadAdapter;
TextView mStackText;
boolean resetInput = false;
boolean hasFinalResult = false;

String mDecimalSeperator;
double memoryValue = Double.NaN;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
.getInstance();
char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
.getDecimalSeparator();
mDecimalSeperator = Character.toString(decimalSeperator);
setContentView(R.layout.main);

// Create the stack
mInputStack = new Stack<String>();
mOperationStack = new Stack<String>();
// Get reference to the keypad button GridView
mKeypadGrid = (GridView) findViewById(R.id.grdButtons);
// Get reference to the user input TextView
userInputText = (TextView) findViewById(R.id.txtInput);
userInputText.setText("0");
memoryStatText = (TextView) findViewById(R.id.txtMemory);
memoryStatText.setText("");
mStackText = (TextView) findViewById(R.id.txtStack);
// Create Keypad Adapter
mKeypadAdapter = new KeypadAdapter(this);
// Set adapter of the keypad grid
mKeypadGrid.setAdapter(mKeypadAdapter);
// Set button click listener of the keypad adapter
mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Button btn = (Button) v;
// Get the KeypadButton value which is used to identify the
// keypad button from the Button's tag
KeypadButton keypadButton = (KeypadButton) btn.getTag();

// Process keypad button
ProcessKeypadInput(keypadButton);
}
});

mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {

}
});

}

private void ProcessKeypadInput(KeypadButton keypadButton) {
//Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
String text = keypadButton.getText().toString();
String currentInput = userInputText.getText().toString();

int currentInputLen = currentInput.length();
String evalResult = null;
double userInputValue = Double.NaN;

switch (keypadButton) {
case BACKSPACE: // Handle backspace
// If has operand skip backspace
if (resetInput)
return;

int endIndex = currentInputLen - 1;

// There is one character at input so reset input to 0
if (endIndex < 1) {
userInputText.setText("0");
}
// Trim last character of the input text
else {
userInputText.setText(currentInput.subSequence(0, endIndex));
}
break;
case SIGN: // Handle -/+ sign
// input has text and is different than initial value 0
if (currentInputLen > 0 && currentInput != "0") {
// Already has (-) sign. Remove that sign
if (currentInput.charAt(0) == '-') {
userInputText.setText(currentInput.subSequence(1,
currentInputLen));
}
// Prepend (-) sign
else {
userInputText.setText("-" + currentInput.toString());
}
}
break;
case CE: // Handle clear input
userInputText.setText("0");
break;
case C: // Handle clear input and stack
userInputText.setText("0");
clearStacks();
break;
case DECIMAL_SEP: // Handle decimal seperator
if (hasFinalResult || resetInput) {
userInputText.setText("0" + mDecimalSeperator);
hasFinalResult = false;
resetInput = false;
} else if (currentInput.contains("."))
return;
else
userInputText.append(mDecimalSeperator);
break;
case DIV:
case PLUS:
case MINUS:
case MULTIPLY:
if (resetInput) {
mInputStack.pop();
mOperationStack.pop();
} else {
if (currentInput.charAt(0) == '-') {
mInputStack.add("(" + currentInput + ")");
} else {
mInputStack.add(currentInput);
}
mOperationStack.add(currentInput);
}

mInputStack.add(text);
mOperationStack.add(text);

dumpInputStack();
evalResult = evaluateResult(false);
if (evalResult != null)
userInputText.setText(evalResult);

resetInput = true;
break;
case CALCULATE:
if (mOperationStack.size() == 0)
break;

mOperationStack.add(currentInput);
evalResult = evaluateResult(true);
if (evalResult != null) {
clearStacks();
userInputText.setText(evalResult);
resetInput = false;
hasFinalResult = true;
}
break;
case M_ADD: // Add user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue += userInputValue;
displayMemoryStat();

hasFinalResult = true;

break;
case M_REMOVE: // Subtract user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue -= userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case MC: // Reset memory buffer to 0
memoryValue = Double.NaN;
displayMemoryStat();
break;
case MR: // Read memoryBuffer value
if (Double.isNaN(memoryValue))
return;
userInputText.setText(doubleToString(memoryValue));
displayMemoryStat();
break;
case MS: // Set memoryBuffer value to user input
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
memoryValue = userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
default:
if (Character.isDigit(text.charAt(0))) {
if (currentInput.equals("0") || resetInput || hasFinalResult) {
userInputText.setText(text);
resetInput = false;
hasFinalResult = false;
} else {
userInputText.append(text);
resetInput = false;
}
}
break;
}
}

private void clearStacks() {
mInputStack.clear();
mOperationStack.clear();
mStackText.setText("");
}

private void dumpInputStack() {
Iterator<String> it = mInputStack.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
CharSequence iValue = it.next();
sb.append(iValue);
}
mStackText.setText(sb.toString());
}

private String evaluateResult(boolean requestedByUser) {
if ((!requestedByUser && mOperationStack.size() != 4)
|| (requestedByUser && mOperationStack.size() != 3))
return null;

String left = mOperationStack.get(0);
String operator = mOperationStack.get(1);
String right = mOperationStack.get(2);
String tmp = null;
if (!requestedByUser)
tmp = mOperationStack.get(3);

double leftVal = Double.parseDouble(left.toString());
double rightVal = Double.parseDouble(right.toString());
double result = Double.NaN;

if (operator.equals(KeypadButton.DIV.getText())) {
result = leftVal / rightVal;
} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
result = leftVal * rightVal;
} else if (operator.equals(KeypadButton.PLUS.getText())) {
result = leftVal + rightVal;
} else if (operator.equals(KeypadButton.MINUS.getText())) {
result = leftVal - rightVal;
}

String resultStr = doubleToString(result);
if (resultStr == null)
return null;

mOperationStack.clear();
if (!requestedByUser) {
mOperationStack.add(resultStr);
mOperationStack.add(tmp);
}

return resultStr;
}

private String doubleToString(double value) {
if (Double.isNaN(value))
return null;

long longVal = (long) value;
if (longVal == value)
return Long.toString(longVal);
else
return Double.toString(value);
}

private double tryParseUserInput() {
String inputStr = userInputText.getText().toString();
double result = Double.NaN;
try {
result = Double.parseDouble(inputStr);

} catch (NumberFormatException nfe) {
}
return result;
}

private void displayMemoryStat() {
if (Double.isNaN(memoryValue)) {
memoryStatText.setText("");
} else {
memoryStatText.setText("M = " + doubleToString(memoryValue));
}
}
}

5)main.xml
========
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/appvertical1" >

<TextView  
   android:id="@+id/txtStack"
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
  android:textSize="15sp"
   android:gravity="right"
   android:background="@drawable/stackview1"
   android:layout_marginTop = "3sp"
   android:layout_marginLeft = "5sp"
   android:layout_marginRight = "5sp"
    android:textColor="@color/darkgrey"/>
    <TextView  
    android:id="@+id/txtInput"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textSize="25sp"
    android:gravity="right"
    android:background="@drawable/inputview1"
    android:textColor="@color/darkgreen"
    android:layout_marginLeft = "5sp"
    android:layout_marginRight = "5sp"/>


    <TextView  
    android:id="@+id/txtMemory"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textSize="15sp"
    android:textColor="@color/lightyellow"
    android:gravity="left"
        android:layout_marginLeft = "5sp"
    android:layout_marginRight = "5sp"/>
<GridView 
    android:id="@+id/grdButtons"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="5"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

</LinearLayout>
6)manifest.xml
==========
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pragmatouch.calculator"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".main"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest> 

PickGalleryImage

1) Create java file ImageGalleryDemoActivity .java
==================================
package com.example.pickgalleryimage;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class ImageGalleryDemoActivity extends Activity {
 
    private ImageView imageView;
   private static int RESULT_LOAD_IMAGE = 1;
 

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.image_gallery_demo);
       imageView = (ImageView) findViewById(R.id.imgView);
       imageView.setOnClickListener(new View.OnClickListener() {
         
           @Override
           public void onClick(View arg0) {
             
               Intent i = new Intent(
                       Intent.ACTION_PICK,
                       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             
               startActivityForResult(i, RESULT_LOAD_IMAGE);
           }
       });
   }
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
     
       if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
           Uri selectedImage = data.getData();
           String[] filePathColumn = { MediaStore.Images.Media.DATA };

           Cursor cursor = getContentResolver().query(selectedImage,
                   filePathColumn, null, null, null);
           cursor.moveToFirst();

           int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
           String picturePath = cursor.getString(columnIndex);
           cursor.close();
           imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
       }
   }
}

2)image_gallery_demo.xml
==================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:layout_weight="1"></ImageView>

</LinearLayout>

Tuesday 11 March 2014

ViewPager Gallery

1)MainActivity.java
==================

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.ViewPager;

public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
MainActivityAdapter adapter = new MainActivityAdapter(this);
viewPager.setAdapter(adapter);
}
}
2)MainActivityAdapter.java
===================
package com.example.viewpagerexample;

import android.content.Context;
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.RelativeLayout;

public class MainActivityAdapter extends PagerAdapter {
LayoutInflater inflater;
TouchImageView imageView;
Context context;
private int[] GalImages = new int[] { R.drawable.eagle, R.drawable.flamingo,
R.drawable.heron,R.drawable.ostrich };

MainActivityAdapter(Context context) {
this.context = context;
}

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

@Override
public int getCount() {
return GalImages.length;
}

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

@Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.layout_fullscreen_image,container, false);
imageView = (TouchImageView)view.findViewById(R.id.imgBig);
int padding = context.getResources().getDimensionPixelSize(R.dimen.margin);
imageView.setPadding(padding, padding, padding, padding);
// imageView.setScaleType(TouchImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(view);
return view;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TouchImageView) object);
}
}
3)TouchImageView.java
==================
package com.example.viewpagerexample;
/*
 * TouchImageView.java
 * By: Michael Ortiz
 * Updated By: Patrick Lackemacher
 * Updated By: Babay88
 * Updated By: @ipsilondev
 * -------------------
 * Extends Android ImageView to include pinch zooming, panning, fling and double tap zoom.
 */

import static com.example.viewpagerexample.TouchImageView.State.ANIMATE_ZOOM;
import static com.example.viewpagerexample.TouchImageView.State.DRAG;
import static com.example.viewpagerexample.TouchImageView.State.FLING;
import static com.example.viewpagerexample.TouchImageView.State.NONE;
import static com.example.viewpagerexample.TouchImageView.State.ZOOM;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.Scroller;

public class TouchImageView extends ImageView {

 private static final String DEBUG = "DEBUG";

 //
 // SuperMin and SuperMax multipliers. Determine how much the image can be
 // zoomed below or above the zoom boundaries, before animating back to the
 // min/max zoom boundary.
 //
 private static final float SUPER_MIN_MULTIPLIER = .75f;
 private static final float SUPER_MAX_MULTIPLIER = 1.25f;

    //
    // Scale of image ranges from minScale to maxScale, where minScale == 1
    // when the image is stretched to fit view.
    //
    private float normalizedScale;
 
    //
    // Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal.
    // MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix
    // saved prior to the screen rotating.
    //
 private Matrix matrix, prevMatrix;

    public static enum State { NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM };
    private State state;

    private float minScale;
    private float maxScale;
    private float superMinScale;
    private float superMaxScale;
    private float[] m;
 
    private Context context;
    private Fling fling;

    //
    // Size of view and previous view size (ie before rotation)
    //
    private int viewWidth, viewHeight, prevViewWidth, prevViewHeight;
 
    //
    // Size of image when it is stretched to fit view. Before and After rotation.
    //
    private float matchViewWidth, matchViewHeight, prevMatchViewWidth, prevMatchViewHeight;
 
    //
    // After setting image, a value of true means the new image should maintain
    // the zoom of the previous image. False means it should be resized within the view.
    //
    private boolean maintainZoomAfterSetImage;
 
    //
    // True when maintainZoomAfterSetImage has been set to true and setImage has been called.
    //
    private boolean setImageCalledRecenterImage;
 
    private ScaleGestureDetector mScaleDetector;
    private GestureDetector mGestureDetector;

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

    public TouchImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        sharedConstructing(context);
    }
 
    public TouchImageView(Context context, AttributeSet attrs, int defStyle) {
     super(context, attrs, defStyle);
     sharedConstructing(context);
    }
 
    private void sharedConstructing(Context context) {
        super.setClickable(true);
        this.context = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        mGestureDetector = new GestureDetector(context, new GestureListener());
        matrix = new Matrix();
        prevMatrix = new Matrix();
        m = new float[9];
        normalizedScale = 1;
        minScale = 1;
        maxScale = 3;
        superMinScale = SUPER_MIN_MULTIPLIER * minScale;
        superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
        maintainZoomAfterSetImage = true;
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);
        setState(NONE);
        setOnTouchListener(new TouchImageViewListener());
    }
 
    @Override
    public void setImageResource(int resId) {
     super.setImageResource(resId);
     setImageCalled();
     savePreviousImageValues();
     fitImageToView();
    }
 
    @Override
    public void setImageBitmap(Bitmap bm) {
     super.setImageBitmap(bm);
     setImageCalled();
     savePreviousImageValues();
     fitImageToView();
    }
 
    @Override
    public void setImageDrawable(Drawable drawable) {
     super.setImageDrawable(drawable);
     setImageCalled();
     savePreviousImageValues();
     fitImageToView();
    }
 
    @Override
    public void setImageURI(Uri uri) {
     super.setImageURI(uri);
     setImageCalled();
     savePreviousImageValues();
     fitImageToView();
    }
 
    private void setImageCalled() {
     if (!maintainZoomAfterSetImage) {
      setImageCalledRecenterImage = true;
     }
    }
 
    /**
     * Save the current matrix and view dimensions
     * in the prevMatrix and prevView variables.
     */
    private void savePreviousImageValues() {
     if (matrix != null) {
      matrix.getValues(m);
      prevMatrix.setValues(m);
      prevMatchViewHeight = matchViewHeight;
         prevMatchViewWidth = matchViewWidth;
         prevViewHeight = viewHeight;
         prevViewWidth = viewWidth;
     }
    }
 
    @Override
    public Parcelable onSaveInstanceState() {
      Bundle bundle = new Bundle();
      bundle.putParcelable("instanceState", super.onSaveInstanceState());
      bundle.putFloat("saveScale", normalizedScale);
      bundle.putFloat("matchViewHeight", matchViewHeight);
      bundle.putFloat("matchViewWidth", matchViewWidth);
      bundle.putInt("viewWidth", viewWidth);
      bundle.putInt("viewHeight", viewHeight);
      matrix.getValues(m);
      bundle.putFloatArray("matrix", m);
      return bundle;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
       if (state instanceof Bundle) {
         Bundle bundle = (Bundle) state;
         normalizedScale = bundle.getFloat("saveScale");
         m = bundle.getFloatArray("matrix");
         prevMatrix.setValues(m);
         prevMatchViewHeight = bundle.getFloat("matchViewHeight");
         prevMatchViewWidth = bundle.getFloat("matchViewWidth");
         prevViewHeight = bundle.getInt("viewHeight");
         prevViewWidth = bundle.getInt("viewWidth");
         super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
         return;
       }

       super.onRestoreInstanceState(state);
    }
 
    /**
     * Get the max zoom multiplier.
     * @return max zoom multiplier.
     */
    public float getMaxZoom() {
     return maxScale;
    }

    /**
     * Set the max zoom multiplier. Default value: 3.
     * @param max max zoom multiplier.
     */
    public void setMaxZoom(float max) {
        maxScale = max;
        superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
    }
 
    /**
     * Get the min zoom multiplier.
     * @return min zoom multiplier.
     */
    public float getMinZoom() {
     return minScale;
    }
 
    /**
     * After setting image, a value of true means the new image should maintain
     * the zoom of the previous image. False means the image should be resized within
     * the view. Defaults value is true.
     * @param maintainZoom
     */
    public void maintainZoomAfterSetImage(boolean maintainZoom) {
     maintainZoomAfterSetImage = maintainZoom;
    }
 
    /**
     * Get the current zoom. This is the zoom relative to the initial
     * scale, not the original resource.
     * @return current zoom multiplier.
     */
    public float getCurrentZoom() {
     return normalizedScale;
    }
 
    /**
     * Set the min zoom multiplier. Default value: 1.
     * @param min min zoom multiplier.
     */
    public void setMinZoom(float min) {
     minScale = min;
     superMinScale = SUPER_MIN_MULTIPLIER * minScale;
    }
 
    /**
     * For a given point on the view (ie, a touch event), returns the
     * point relative to the original drawable's coordinate system.
     * @param x
     * @param y
     * @return PointF relative to original drawable's coordinate system.
     */
    public PointF getDrawablePointFromTouchPoint(float x, float y) {
     return transformCoordTouchToBitmap(x, y, true);
    }
 
    /**
     * For a given point on the view (ie, a touch event), returns the
     * point relative to the original drawable's coordinate system.
     * @param p
     * @return PointF relative to original drawable's coordinate system.
     */
    public PointF getDrawablePointFromTouchPoint(PointF p) {
     return transformCoordTouchToBitmap(p.x, p.y, true);
    }
 
    /**
     * Performs boundary checking and fixes the image matrix if it
     * is out of bounds.
     */
    private void fixTrans() {
        matrix.getValues(m);
        float transX = m[Matrix.MTRANS_X];
        float transY = m[Matrix.MTRANS_Y];
     
        float fixTransX = getFixTrans(transX, viewWidth, getImageWidth());
        float fixTransY = getFixTrans(transY, viewHeight, getImageHeight());
     
        if (fixTransX != 0 || fixTransY != 0) {
            matrix.postTranslate(fixTransX, fixTransY);
        }
    }
 
    /**
     * When transitioning from zooming from focus to zoom from center (or vice versa)
     * the image can become unaligned within the view. This is apparent when zooming
     * quickly. When the content size is less than the view size, the content will often
     * be centered incorrectly within the view. fixScaleTrans first calls fixTrans() and
     * then makes sure the image is centered correctly within the view.
     */
    private void fixScaleTrans() {
     fixTrans();
     matrix.getValues(m);
     if (getImageWidth() < viewWidth) {
      m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2;
     }
   
     if (getImageHeight() < viewHeight) {
      m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2;
     }
     matrix.setValues(m);
    }

    private 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;
    }
 
    private float getFixDragTrans(float delta, float viewSize, float contentSize) {
        if (contentSize <= viewSize) {
            return 0;
        }
        return delta;
    }
 
    private float getImageWidth() {
     return matchViewWidth * normalizedScale;
    }
 
    private float getImageHeight() {
     return matchViewHeight * normalizedScale;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable drawable = getDrawable();
        if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
         setMeasuredDimension(0, 0);
         return;
        }
     
        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        viewWidth = setViewSize(widthMode, widthSize, drawableWidth);
        viewHeight = setViewSize(heightMode, heightSize, drawableHeight);
     
        //
        // Set view dimensions
        //
        setMeasuredDimension(viewWidth, viewHeight);
     
        //
        // Fit content within view
        //
        fitImageToView();
    }
 
    /**
     * If the normalizedScale is equal to 1, then the image is made to fit the screen. Otherwise,
     * it is made to fit the screen according to the dimensions of the previous image matrix. This
     * allows the image to maintain its zoom after rotation.
     */
    private void fitImageToView() {
     Drawable drawable = getDrawable();
        if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
         return;
        }
        if (matrix == null || prevMatrix == null) {
         return;
        }
     
        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();
   
     //
     // Scale image for view
     //
        float scaleX = (float) viewWidth / drawableWidth;
        float scaleY = (float) viewHeight / drawableHeight;
        float scale = Math.min(scaleX, scaleY);

        //
        // Center the image
        //
        float redundantYSpace = viewHeight - (scale * drawableHeight);
        float redundantXSpace = viewWidth - (scale * drawableWidth);
        matchViewWidth = viewWidth - redundantXSpace;
        matchViewHeight = viewHeight - redundantYSpace;
        if (normalizedScale == 1 || setImageCalledRecenterImage) {
         //
         // Stretch and center image to fit view
         //
         matrix.setScale(scale, scale);
         matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
         normalizedScale = 1;
         setImageCalledRecenterImage = false;
       
        } else {
         prevMatrix.getValues(m);
       
         //
         // Rescale Matrix after rotation
         //
         m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * normalizedScale;
         m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * normalizedScale;
       
         //
         // TransX and TransY from previous matrix
         //
            float transX = m[Matrix.MTRANS_X];
            float transY = m[Matrix.MTRANS_Y];
         
            //
            // Width
            //
            float prevActualWidth = prevMatchViewWidth * normalizedScale;
            float actualWidth = getImageWidth();
            translateMatrixAfterRotate(Matrix.MTRANS_X, transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth);
         
            //
            // Height
            //
            float prevActualHeight = prevMatchViewHeight * normalizedScale;
            float actualHeight = getImageHeight();
            translateMatrixAfterRotate(Matrix.MTRANS_Y, transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight);
         
            //
            // Set the matrix to the adjusted scale and translate values.
            //
            matrix.setValues(m);
        }
        setImageMatrix(matrix);
    }
 
    /**
     * Set view dimensions based on layout params
     *
     * @param mode
     * @param size
     * @param drawableWidth
     * @return
     */
    private int setViewSize(int mode, int size, int drawableWidth) {
     int viewSize;
     switch (mode) {
  case MeasureSpec.EXACTLY:
   viewSize = size;
   break;
 
  case MeasureSpec.AT_MOST:
   viewSize = Math.min(drawableWidth, size);
   break;
 
  case MeasureSpec.UNSPECIFIED:
   viewSize = drawableWidth;
   break;
 
  default:
   viewSize = size;
    break;
  }
     return viewSize;
    }
 
    /**
     * After rotating, the matrix needs to be translated. This function finds the area of image
     * which was previously centered and adjusts translations so that is again the center, post-rotation.
     *
     * @param axis Matrix.MTRANS_X or Matrix.MTRANS_Y
     * @param trans the value of trans in that axis before the rotation
     * @param prevImageSize the width/height of the image before the rotation
     * @param imageSize width/height of the image after rotation
     * @param prevViewSize width/height of view before rotation
     * @param viewSize width/height of view after rotation
     * @param drawableSize width/height of drawable
     */
    private void translateMatrixAfterRotate(int axis, float trans, float prevImageSize, float imageSize, int prevViewSize, int viewSize, int drawableSize) {
     if (imageSize < viewSize) {
         //
         // The width/height of image is less than the view's width/height. Center it.
         //
         m[axis] = (viewSize - (drawableSize * m[Matrix.MSCALE_X])) * 0.5f;
       
        } else if (trans > 0) {
         //
         // The image is larger than the view, but was not before rotation. Center it.
         //
         m[axis] = -((imageSize - viewSize) * 0.5f);
       
        } else {
         //
         // Find the area of the image which was previously centered in the view. Determine its distance
         // from the left/top side of the view as a fraction of the entire image's width/height. Use that percentage
         // to calculate the trans in the new view width/height.
         //
         float percentage = (Math.abs(trans) + (0.5f * prevViewSize)) / prevImageSize;
         m[axis] = -((percentage * imageSize) - (viewSize * 0.5f));
        }
    }
 
    private void setState(State state) {
     this.state = state;
    }
 
    /**
     * Gesture Listener detects a single click or long click and passes that on
     * to the view's listener.
     * @author Ortiz
     *
     */
    private class GestureListener extends GestureDetector.SimpleOnGestureListener {
   
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e)
        {
         return performClick();
        }
     
        @Override
        public void onLongPress(MotionEvent e)
        {
         performLongClick();
        }
     
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
        {
         if (fling != null) {
          //
          // If a previous fling is still active, it should be cancelled so that two flings
          // are not run simultaenously.
          //
          fling.cancelFling();
         }
         fling = new Fling((int) velocityX, (int) velocityY);
         compatPostOnAnimation(fling);
         return super.onFling(e1, e2, velocityX, velocityY);
        }
     
        @Override
        public boolean onDoubleTap(MotionEvent e) {
         boolean consumed = false;
         if (state == NONE) {
          float targetZoom = (normalizedScale == minScale) ? maxScale : minScale;
          DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, e.getX(), e.getY(), false);
          compatPostOnAnimation(doubleTap);
          consumed = true;
         }
         return consumed;
        }
    }
 
    /**
     * Responsible for all touch events. Handles the heavy lifting of drag and also sends
     * touch events to Scale Detector and Gesture Detector.
     * @author Ortiz
     *
     */
    private class TouchImageViewListener implements OnTouchListener {
   
     //
        // Remember last point position for dragging
        //
        private PointF last = new PointF();
   
     @Override
        public boolean onTouch(View v, MotionEvent event) {
            mScaleDetector.onTouchEvent(event);
            mGestureDetector.onTouchEvent(event);
            PointF curr = new PointF(event.getX(), event.getY());
         
            if (state == NONE || state == DRAG || state == FLING) {
             switch (event.getAction()) {
                 case MotionEvent.ACTION_DOWN:
                  last.set(curr);
                     if (fling != null)
                      fling.cancelFling();
                     setState(DRAG);
                     break;
                 
                 case MotionEvent.ACTION_MOVE:
                     if (state == DRAG) {
                         float deltaX = curr.x - last.x;
                         float deltaY = curr.y - last.y;
                         float fixTransX = getFixDragTrans(deltaX, viewWidth, getImageWidth());
                         float fixTransY = getFixDragTrans(deltaY, viewHeight, getImageHeight());
                         matrix.postTranslate(fixTransX, fixTransY);
                         fixTrans();
                         last.set(curr.x, curr.y);
                     }
                     break;

                 case MotionEvent.ACTION_UP:
                 case MotionEvent.ACTION_POINTER_UP:
                     setState(NONE);
                     break;
             }
            }
         
            setImageMatrix(matrix);
            //
            // indicate event was handled
            //
            return true;
        }
    }

    /**
     * ScaleListener detects user two finger scaling and scales image.
     * @author Ortiz
     *
     */
    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            setState(ZOOM);
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
         scaleImage(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY(), true);
            return true;
        }
     
        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
         super.onScaleEnd(detector);
         setState(NONE);
         boolean animateToZoomBoundary = false;
         float targetZoom = normalizedScale;
         if (normalizedScale > maxScale) {
          targetZoom = maxScale;
          animateToZoomBoundary = true;
       
         } else if (normalizedScale < minScale) {
          targetZoom = minScale;
          animateToZoomBoundary = true;
         }
       
         if (animateToZoomBoundary) {
          DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, viewWidth / 2, viewHeight / 2, true);
          compatPostOnAnimation(doubleTap);
         }
        }
    }
 
    private void scaleImage(float deltaScale, float focusX, float focusY, boolean stretchImageToSuper) {
   
     float lowerScale, upperScale;
     if (stretchImageToSuper) {
      lowerScale = superMinScale;
      upperScale = superMaxScale;
   
     } else {
      lowerScale = minScale;
      upperScale = maxScale;
     }
   
     float origScale = normalizedScale;
        normalizedScale *= deltaScale;
        if (normalizedScale > upperScale) {
            normalizedScale = upperScale;
            deltaScale = upperScale / origScale;
        } else if (normalizedScale < lowerScale) {
            normalizedScale = lowerScale;
            deltaScale = lowerScale / origScale;
        }
     
        matrix.postScale(deltaScale, deltaScale, focusX, focusY);
        fixScaleTrans();
    }
 
    /**
     * DoubleTapZoom calls a series of runnables which apply
     * an animated zoom in/out graphic to the image.
     * @author Ortiz
     *
     */
    private class DoubleTapZoom implements Runnable {
   
     private long startTime;
     private static final float ZOOM_TIME = 500;
     private float startZoom, targetZoom;
     private float bitmapX, bitmapY;
     private boolean stretchImageToSuper;
     private AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
     private PointF startTouch;
     private PointF endTouch;

     DoubleTapZoom(float targetZoom, float focusX, float focusY, boolean stretchImageToSuper) {
      setState(ANIMATE_ZOOM);
      startTime = System.currentTimeMillis();
      this.startZoom = normalizedScale;
      this.targetZoom = targetZoom;
      this.stretchImageToSuper = stretchImageToSuper;
      PointF bitmapPoint = transformCoordTouchToBitmap(focusX, focusY, false);
      this.bitmapX = bitmapPoint.x;
      this.bitmapY = bitmapPoint.y;
   
      //
      // Used for translating image during scaling
      //
      startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY);
      endTouch = new PointF(viewWidth / 2, viewHeight / 2);
     }

  @Override
  public void run() {
   float t = interpolate();
   float deltaScale = calculateDeltaScale(t);
   scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper);
   translateImageToCenterTouchPosition(t);
   fixScaleTrans();
   setImageMatrix(matrix);
 
   if (t < 1f) {
    //
    // We haven't finished zooming
    //
    compatPostOnAnimation(this);
 
   } else {
    //
    // Finished zooming
    //
    setState(NONE);
   }
  }

  /**
   * Interpolate between where the image should start and end in order to translate
   * the image so that the point that is touched is what ends up centered at the end
   * of the zoom.
   * @param t
   */
  private void translateImageToCenterTouchPosition(float t) {
   float targetX = startTouch.x + t * (endTouch.x - startTouch.x);
   float targetY = startTouch.y + t * (endTouch.y - startTouch.y);
   PointF curr = transformCoordBitmapToTouch(bitmapX, bitmapY);
   matrix.postTranslate(targetX - curr.x, targetY - curr.y);
  }

  /**
   * Use interpolator to get t
   * @return
   */
  private float interpolate() {
   long currTime = System.currentTimeMillis();
   float elapsed = (currTime - startTime) / ZOOM_TIME;
   elapsed = Math.min(1f, elapsed);
   return interpolator.getInterpolation(elapsed);
  }

  /**
   * Interpolate the current targeted zoom and get the delta
   * from the current zoom.
   * @param t
   * @return
   */
  private float calculateDeltaScale(float t) {
   float zoom = startZoom + t * (targetZoom - startZoom);
   return zoom / normalizedScale;
  }
    }
 
    /**
     * This function will transform the coordinates in the touch event to the coordinate
     * system of the drawable that the imageview contain
     * @param x x-coordinate of touch event
     * @param y y-coordinate of touch event
     * @param clipToBitmap Touch event may occur within view, but outside image content. True, to clip return value
     *    to the bounds of the bitmap size.
     * @return Coordinates of the point touched, in the coordinate system of the original drawable.
     */
    private PointF transformCoordTouchToBitmap(float x, float y, boolean clipToBitmap) {
         matrix.getValues(m);
         float origW = getDrawable().getIntrinsicWidth();
         float origH = getDrawable().getIntrinsicHeight();
         float transX = m[Matrix.MTRANS_X];
         float transY = m[Matrix.MTRANS_Y];
         float finalX = ((x - transX) * origW) / getImageWidth();
         float finalY = ((y - transY) * origH) / getImageHeight();
     
         if (clipToBitmap) {
          finalX = Math.min(Math.max(x, 0), origW);
          finalY = Math.min(Math.max(y, 0), origH);
         }
     
         return new PointF(finalX , finalY);
    }
 
    /**
     * Inverse of transformCoordTouchToBitmap. This function will transform the coordinates in the
     * drawable's coordinate system to the view's coordinate system.
     * @param bx x-coordinate in original bitmap coordinate system
     * @param by y-coordinate in original bitmap coordinate system
     * @return Coordinates of the point in the view's coordinate system.
     */
    private PointF transformCoordBitmapToTouch(float bx, float by) {
        matrix.getValues(m);    
        float origW = getDrawable().getIntrinsicWidth();
        float origH = getDrawable().getIntrinsicHeight();
        float px = bx / origW;
        float py = by / origH;
        float finalX = m[Matrix.MTRANS_X] + getImageWidth() * px;
        float finalY = m[Matrix.MTRANS_Y] + getImageHeight() * py;
        return new PointF(finalX , finalY);
    }
 
    /**
     * Fling launches sequential runnables which apply
     * the fling graphic to the image. The values for the translation
     * are interpolated by the Scroller.
     * @author Ortiz
     *
     */
    private class Fling implements Runnable {
   
        Scroller scroller;
     int currX, currY;
   
     Fling(int velocityX, int velocityY) {
      setState(FLING);
      scroller = new Scroller(context);
      matrix.getValues(m);
   
      int startX = (int) m[Matrix.MTRANS_X];
      int startY = (int) m[Matrix.MTRANS_Y];
      int minX, maxX, minY, maxY;
   
      if (getImageWidth() > viewWidth) {
       minX = viewWidth - (int) getImageWidth();
       maxX = 0;
     
      } else {
       minX = maxX = startX;
      }
   
      if (getImageHeight() > viewHeight) {
       minY = viewHeight - (int) getImageHeight();
       maxY = 0;
     
      } else {
       minY = maxY = startY;
      }
   
      scroller.fling(startX, startY, (int) velocityX, (int) velocityY, minX,
                    maxX, minY, maxY);
      currX = startX;
      currY = startY;
     }
   
     public void cancelFling() {
      if (scroller != null) {
       setState(NONE);
       scroller.forceFinished(true);
      }
     }
   
  @Override
  public void run() {
   if (scroller.isFinished()) {
          scroller = null;
          return;
         }
 
   if (scroller.computeScrollOffset()) {
          int newX = scroller.getCurrX();
             int newY = scroller.getCurrY();
             int transX = newX - currX;
             int transY = newY - currY;
             currX = newX;
             currY = newY;
             matrix.postTranslate(transX, transY);
             fixTrans();
             setImageMatrix(matrix);
             compatPostOnAnimation(this);
         }
  }
    }
 
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 private void compatPostOnAnimation(Runnable runnable) {
     if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
            postOnAnimation(runnable);
         
        } else {
            postDelayed(runnable, 1000/60);
        }
    }
 
    private void printMatrixInfo() {
     matrix.getValues(m);
     Log.d(DEBUG, "Scale: " + m[Matrix.MSCALE_X] + " TransX: " + m[Matrix.MTRANS_X] + " TransY: " + m[Matrix.MTRANS_Y]);
    }

}
4)activity_main.xml
=============
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >


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

</RelativeLayout>
5)layout_fullscreen_image.xml
====================
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000" >
     <ImageView
        android:id="@+id/imgClose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:visibility="visible"
        android:contentDescription="@string/app_name"
        android:src="@drawable/ic_launcher" />
   
    <com.example.viewpagerexample.TouchImageView
        android:id="@+id/imgBig"
        android:layout_below="@id/imgClose"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter" />
</RelativeLayout>