How to stop swipe at some point in ItemTouchHelpers? - java

I need to swipe an item at the beginning, or did a full swipe, or stopped in current point. As in the Yandex mail. I was tring to do setLeft(dx) and setRight(dx) but that's not what I need
I have class
ItemTouchHelperCallback extends ItemTouchHelper.Callback
and inside i override method
#Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
View itemView = viewHolder.itemView;
// not sure why, but this method get's called for viewholder that are already swiped away
if (viewHolder.getAdapterPosition() == -1) {
// not interested in those
return;
}
float height = (float) itemView.getBottom() - (float) itemView.getTop();
float width = height / 3;
float temdX=0;
Bitmap icon;
if(dX > 0 || lastdX>0){
//try stop item while back in dx=0, but workin only while i debug
if(lastdX>=100 && dX==0 &&lastdX!=0 &&lastdX!=-720)
{
dX=100;
isCurrentlyActive=true;
}
lastdX=dX;
itemView.setLeft((int) dX);
p.setColor(Color.GREEN);
RectF background = new RectF((float) itemView.getLeft(), (float) itemView.getTop(), dX,(float) itemView.getBottom());
c.drawRect(background,p);
icon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_y);
RectF icon_dest = new RectF((float) itemView.getLeft() + width ,(float) itemView.getTop() + width, (float) itemView.getLeft()+ 2*width,(float)itemView.getBottom() - width);
c.drawBitmap(icon, null, icon_dest, p);
} else if(lastdX<0 || dX<0) {
if(lastdX<=-100 && dX==0 &&lastdX!=0 &&lastdX!=720)
{
dX=-100;
//itemView.setTranslationX(-200);
isCurrentlyActive=true;
}
lastdX=dX;
itemView.setRight((int)(dX));
p.setColor(Color.RED);
RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(),(float) itemView.getRight(), (float) itemView.getBottom());
c.drawRect(background,p);
icon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_x);
RectF icon_dest = new RectF((float) itemView.getRight() - 2*width ,(float) itemView.getTop() + width, (float) itemView.getRight() - width,(float)itemView.getBottom() - width);
c.drawBitmap(icon,null,icon_dest,p);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}

I needed to do something similar and at the beginning I also thought to use the callbacks provided in the ItemTouchHelper. It turned out it's not the right approach.
If you want to stop (or in general to control) the translation of the view during the swipe, you need to be able to modify and save the value of the displacement dX. If you use the ItemTouchHelper, this value is controlled outside the available callbacks.
The solution for me was the implementation of the swipe with a custom touchListener, attached in the view holder of the recycler view. You can find an example of the basic implementation here. In case you need to consider the click on the item, remember you need to implement this in the touchListener as well.
I hope this is somehow helpful.
EDIT
Here a snippet of a custom ItemTouchListener. The listener is simplified and shows only code to handle the translation on the view during swipe. In order to stop swipe, just implement limit logic on translationX under ACTION_MOVE.
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
public class ItemTouchListener implements View.OnTouchListener {
private int mSlop;
private View mView;
private float mDownX, mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private float mTranslationX;
public ItemTouchListener(View view) {
ViewConfiguration vc = ViewConfiguration.get(view.getContext());
mSlop = vc.getScaledTouchSlop();
mView = view;
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// offset because the view is translated during swipe
motionEvent.offsetLocation(mTranslationX, 0);
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
return true;
}
case MotionEvent.ACTION_UP: {
// if needed, implement part of limit swipe logic also here
if (mVelocityTracker == null) {
break;
}
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
mVelocityTracker.recycle();
mVelocityTracker = null;
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
// cancel view's touch
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
cancelEvent.recycle();
}
if (mSwiping) {
// limit deltaX here: this will keep the swipe up to desired point
mTranslationX = deltaX;
mView.setTranslationX(deltaX - mSwipingSlop);
return true;
}
break;
}
}
return false;
}
}

Related

Picure Click to Picture Drag in Android Puzzle game

I Have tried with all possible ways which is suggested in StackOverflow
But i can't able to change from click to drag
OnTouch event is used for click.. and my images get clicked in this. and i can't able to drag and drop the image. i need to drag the image instead of clicking...
I will be much thankful to you. if you help me on this part
i have also tried this scenario's
Drag and Drop and OnClick TextView
But i didn't get any result. so please can anyone help me!!!!!!!
Can anyone help me in this ??
public class TouchListener implements View.OnTouchListener {
private float xDelta;
private float yDelta;
private PuzzleActivity activity;
public TouchListener(PuzzleActivity activity) {
this.activity = activity;
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getRawX();
float y = motionEvent.getRawY();
final double tolerance = sqrt(pow(view.getWidth(), 2) + pow(view.getHeight(), 2)) / 10;
PuzzlePiece piece = (PuzzlePiece) view;
if (!piece.canMove) {
return true;
}
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
xDelta = x - lParams.leftMargin;
yDelta = y - lParams.topMargin;
piece.bringToFront();
break;
case MotionEvent.ACTION_MOVE:
lParams.leftMargin = (int) (x - xDelta);
lParams.topMargin = (int) (y - yDelta);
view.setLayoutParams(lParams);
break;
case MotionEvent.ACTION_UP:
int xDiff = abs(piece.xCoord - lParams.leftMargin);
int yDiff = abs(piece.yCoord - lParams.topMargin);
if (xDiff <= tolerance && yDiff <= tolerance) {
lParams.leftMargin = piece.xCoord;
lParams.topMargin = piece.yCoord;
piece.setLayoutParams(lParams);
piece.canMove = false;
sendViewToBack(piece);
activity.checkGameOver();
}
break;
}
return true;
}
public void sendViewToBack(final View child) {
final ViewGroup parent = (ViewGroup)child.getParent();
if (null != parent) {
parent.removeView(child);
parent.addView(child, 0);
}
}
}

Dialogfragment dynamic grow animation on image item click

I created the recyclerview with grid layout manager. When any one clicks on the image thumbnail the image should be expanded to full screen in Dialogfragment which has view pager with the animation from the thumb clicked.
I have tried the different solution but not worked. The animation directly applied from the styles working but how to define the dynamic runtime animation.
I had tried the following but not working exactly.
Any idea on how to achieve this thing??
MediaFragment.java
#Override
public void onItemClick(View v, int position) {
switch (v.getId()) {
case R.id.llItemContainer:
Bundle bundle = new Bundle();
bundle.putInt(Constant.KEY_CURRENT_ITEM, position);
dialogMediaProfileFragment = new DialogMediaProfileFragment();
dialogMediaProfileFragment.setArguments(bundle);
dialogMediaProfileFragment.show(getFragmentManager(), TAG);
zoomImageFromThumb(v).start();
break;
}
}
private Animator zoomImageFromThumb(final View thumbView) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
startBounds = new Rect();
finalBounds = new Rect();
Point globalOffset = new Point();
thumbView.getGlobalVisibleRect(startBounds);
rvMediaPost.getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds
.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
setAlpha(thumbView, 1f);
//This shows the nullpointer exception
/*setPivotX(dialogMediaProfileFragment.getView(), 0f);
setPivotY(dialogMediaProfileFragment.getView(), 0f);*/
AnimatorSet set = new AnimatorSet();
set.play(
ObjectAnimator.ofFloat(dialogMediaProfileFragment, "translationX",
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(dialogMediaProfileFragment, "translationY",
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(dialogMediaProfileFragment, "scaleX",
startScale, 1f))
.with(ObjectAnimator.ofFloat(dialogMediaProfileFragment, "scaleY",
startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
return mCurrentAnimator = set;
}
private void setAlpha(View view, float alpha) {
view.setAlpha(alpha);
}
private void setPivotX(View view, float x) {
view.setPivotX(x);
}
private void setPivotY(View view, float y) {
view.setPivotY(y);
}
#Jaymin Panchal,
You have to implement customize Android Activity Transition animation.
Also you can refer this code snippet for more on about your requirement.

ViewPager Disable Swiping

I have a ViewPager which has 3 fragments. Fragment A on the left, B in the middle and C on the right. Fragment C has a ListView which fills the whole width of the screen. I implemented a swipe listener on my ListView items using the following code:
SWIPE DETECTOR :
public class SwipeDetector implements View.OnTouchListener {
public static enum Action {
LR, // Left to Right
RL, // Right to Left
TB, // Top to bottom
BT, // Bottom to Top
None // when no action was detected
}
private static final String logTag = "SwipeDetector";
private static final int MIN_DISTANCE = 100;
private static final int VERTICAL_MIN_DISTANCE = 80;
private static final int HORIZONTAL_MIN_DISTANCE = 80;
private float downX, downY, upX, upY;
private Action mSwipeDetected = Action.None;
public boolean swipeDetected() {
return mSwipeDetected != Action.None;
}
public Action getAction() {
return mSwipeDetected;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
downY = event.getY();
mSwipeDetected = Action.None;
return false; // allow other events like Click to be processed
}
case MotionEvent.ACTION_MOVE: {
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
// horizontal swipe detection
if (Math.abs(deltaX) > HORIZONTAL_MIN_DISTANCE) {
// left or right
if (deltaX < 0) {
// Log.i(logTag, "Swipe Left to Right");
mSwipeDetected = Action.LR;
return true;
}
if (deltaX > 0) {
// Log.i(logTag, "Swipe Right to Left");
mSwipeDetected = Action.RL;
return true;
}
} else
// vertical swipe detection
if (Math.abs(deltaY) > VERTICAL_MIN_DISTANCE) {
// top or down
if (deltaY < 0) {
Log.i(logTag, "Swipe Top to Bottom");
mSwipeDetected = Action.TB;
return false;
}
if (deltaY > 0) {
Log.i(logTag, "Swipe Bottom to Top");
mSwipeDetected = Action.BT;
return false;
}
}
return true;
}
}
return false;
}}
I use it in the following way :
listView.setOnTouchListener(swipeDetector);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
Log.d("CLICKED", "CLICKED");
if (swipeDetector.swipeDetected()) {
Log.d("SWIPING", "SWIPING");
Log.d("ACTION", swipeDetector.getAction().toString());
final Button del = (Button) view.findViewById(R.id.delete_button);
if (swipeDetector.getAction() == SwipeDetector.Action.LR) {
Log.d("LEFT TO RIGHT", "Left to right");
This works perfectly fine with Activities. However, the problem now is that when I swipe, it assumes I am swiping in the ViewPager and takes me back to the middle fragment. Is there a way to disable the ViewPager swiping on this ListView or change the focus so that this works?

Pinch zoom ImageView - Want to scale whole image beyond size of screen

I have pinch zooming for an image, however when I first load the app the whole of the image is not visible, only a portion. The image fills the width of the screen but there is white-space above and below it. Also when the image is scaled the image becomes very short. The aspect ratio should stay the same.
I would like to have the whole image visible when the app loads and then I want to be able to zoom out with two fingers where the image doesn't become smaller than the size of the screen, so that the screen is always full (the image is a map).
For zooming in, the image should scale beyond the width and height of the phone screen. That way I can pan across to view the map in detail.
Any help would be greatly appreciated. Related code is below.
My MainActivity code:
public class MainActivity extends Activity
{
private MapView image;
private Matrix matrix = new Matrix();
float mLastTouchX, mPosX;
float mLastTouchY, mPosY;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1f;
private int mActivePointerId = MotionEvent.INVALID_POINTER_ID;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (MapView)findViewById(R.id.imageView1);
mScaleDetector = new ScaleGestureDetector(MainActivity.this, new ScaleListener());
}
public void onDraw(Canvas canvas)
{
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
mScaleDetector.onTouchEvent(event);
final int action = MotionEventCompat.getActionMasked(event);
switch (action)
{
case MotionEvent.ACTION_DOWN:
{
final int pointerIndex = MotionEventCompat.getActionIndex(event);
final float x = MotionEventCompat.getX(event, pointerIndex);
final float y = MotionEventCompat.getY(event, pointerIndex);
// Remember where we started (for dragging)
mLastTouchX = x;
mLastTouchY = y;
// Save the ID of this pointer (for dragging)
mActivePointerId = MotionEventCompat.getPointerId(event, 0);
break;
}
case MotionEvent.ACTION_MOVE:
{
// Find the index of the active pointer and fetch its position
final int pointerIndex =
MotionEventCompat.findPointerIndex(event, mActivePointerId);
final float x = MotionEventCompat.getX(event, pointerIndex);
final float y = MotionEventCompat.getY(event, pointerIndex);
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP:
{
mActivePointerId = MotionEvent.INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL:
{
mActivePointerId = MotionEvent.INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP:
{
final int pointerIndex = MotionEventCompat.getActionIndex(event);
final int pointerId = MotionEventCompat.getPointerId(event, pointerIndex);
if (pointerId == mActivePointerId)
{
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = MotionEventCompat.getX(event, newPointerIndex);
mLastTouchY = MotionEventCompat.getY(event, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(event, newPointerIndex);
}
break;
}
}
image.setX(mPosX);
image.setY(mPosY);
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
#Override
public boolean onScale(ScaleGestureDetector detector)
{
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
matrix.setScale(mScaleFactor, mScaleFactor);
image.setImageMatrix(matrix);
return true;
}
}
}
Custom ImageView:
public class MapView extends ImageView
{
public MapView(final Context context, final AttributeSet attrs)
{
super(context, attrs);
}
public void scaleImage(int boundBoxInDp)
{
Drawable drawable = getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float xScale = ((float) boundBoxInDp) / width;
float yScale = ((float) boundBoxInDp) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
// Apply the scaled bitmap
setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)getLayoutParams();
params.width = width;
params.height = height;
setLayoutParams(params);
}
private int dpToPx(Context c, int dp)
{
float density = c.getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
#Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec)
{
final Drawable d = this.getDrawable();
if (d != null)
{
// ceil not round - avoid thin vertical gaps along the left/right edges
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
this.setMeasuredDimension(width, height);
}
else
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<com.kilobolt.framework.locationfinder.MapView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="matrix"
android:src="#drawable/uea" />
</RelativeLayout>
I took a different approach to solve the problem of displaying a custom map. Instead of displaying a fixed sized image, I used Google Maps Javascript API v3 (https://developers.google.com/maps/documentation/javascript/examples/marker-simple).
I displayed this in a web view and created a reusable function in javascript to create custom markers.
If anyone comes across this issue, which appears to not to be well documented, give this map solution a try, and feel free to message me. Hope this helps.

how to set default image size in image view with zoom in zoom out?

I am using horizontal scrollview, and when I am clicking on the image buttom of horizontal scrollview, then my image is showing in the imageview. This functionality is working properly.
And in the image view I am able to zoom the image. But after zooming, when I am clicking on the next image button of scrollview then, imageview bydefault showing zoomed image. Actually it is taking zoom of previous image. So my problem is that how can I remove previous zoom, for next image. I mean next image must come with default size, not already zoomed.
Here is my code.
public class ViewButtonActivity extends Activity implements OnClickListener,
OnTouchListener {
ImageView imgView;
private ProgressDialog pDialog;
public static boolean isTouch = false;
ImageButton imgButton1, imgButton2, imgButton3, imgButton4, imgButton5;
HorizontalScrollView horizontalScrollView;
public ImageLoader imageLoader;
public static String[] imageUrl = {
"http://0-03/_cover.jpg",
"http://www.magazine.jpg",
"http://large_1.jpg",
"http://4.bp.Apr2011.jpg",
"http://www.theof.com/git.jpg" };
private int mImageHeight, mImageWidth;
private static final String TAG = "Touch";
private static final float MIN_ZOOM = 1f, MAX_ZOOM = 1f;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_button_click_activity);
imageLoader = new ImageLoader(getApplicationContext());
imgView = (ImageView) findViewById(R.id.image_view);
imgButton1 = (ImageButton) findViewById(R.id.imageButton1);
imgButton2 = (ImageButton) findViewById(R.id.imageButton2);
imgButton3 = (ImageButton) findViewById(R.id.imageButton3);
imgButton4 = (ImageButton) findViewById(R.id.imageButton4);
imgButton5 = (ImageButton) findViewById(R.id.imageButton5);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontal_scroll_view);
imageLoader.DisplayImage(imageUrl[0], imgButton1);
imageLoader.DisplayImage(imageUrl[1], imgButton2);
imageLoader.DisplayImage(imageUrl[2], imgButton3);
imageLoader.DisplayImage(imageUrl[3], imgButton4);
imageLoader.DisplayImage(imageUrl[4], imgButton5);
imgButton1.setOnClickListener(this);
imgButton2.setOnClickListener(this);
imgButton3.setOnClickListener(this);
imgButton4.setOnClickListener(this);
imgButton5.setOnClickListener(this);
mImageHeight = imgView.getWidth();
mImageWidth = imgView.getHeight();
imgView.setOnTouchListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
imageLoader.DisplayImage(imageUrl[0], imgView);
break;
case R.id.imageButton2:
imageLoader.DisplayImage(imageUrl[1], imgView);
break;
case R.id.imageButton3:
imageLoader.DisplayImage(imageUrl[2], imgView);
break;
case R.id.imageButton4:
imageLoader.DisplayImage(imageUrl[3], imgView);
break;
case R.id.imageButton5:
imageLoader.DisplayImage(imageUrl[4], imgView);
// imgView.setImageResource(R.drawable.img5);
break;
}
}
public boolean onTouch(View v, MotionEvent event) {
ImageView imgView = (ImageView) v;
imgView.setScaleType(ImageView.ScaleType.MATRIX);
float scale;
dumpEvent(event);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG"); // write to LogCat
mode = DRAG;
break;
case MotionEvent.ACTION_UP: // first finger lifted
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 5f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY()
- start.y); // create the transformation in the matrix
// of points
} else if (mode == ZOOM) {
// pinch zooming
float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 5f) {
matrix.set(savedMatrix);
scale = newDist / oldDist; // setting the scaling of the
// matrix...if scale > 1 means
// zoom in...if scale < 1 means
// zoom out
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
imgView.setImageMatrix(matrix);
return true;
}
private float spacing(MotionEvent event)
{
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event)
{
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
private void dumpEvent(MotionEvent event)
{
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE","POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP)
{
sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++)
{
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d("Touch Events ---------", sb.toString());
}
}
Presumably you have to reset to the original value of the Matrix which contains the current state of the transformation (which includes zoom)? I see you already keep track of the Matrix, what's standing in your way resetting it to the old value when you advance to the next image during onClick()?

Categories