Code example for VelocityTracker

Methods: addMovement, computeCurrentVelocity, getXVelocity, getYVelocity, recycle

0
	final float y = event.getY();
 
	if (mVelocityTracker == null) {
	    mVelocityTracker = VelocityTracker.obtain();
	} 
	mVelocityTracker.addMovement(event);
 
	switch (action) {
	case MotionEvent.ACTION_DOWN:
	    mZoomControl.stopFling();
	    mDownX = x;
	    mDownY = y;
	    mX = x;
	    mY = y;
	    break; 
 
	case MotionEvent.ACTION_POINTER_DOWN:
	    if (event.getPointerCount() > 1) {
		oldDist = spacing(event);
		if (oldDist > 10f) {
		    midPoint(mMidPoint, event);
		    mMode = Mode.PINCHZOOM;
		} 
	    } 
	    break; 
 
	case MotionEvent.ACTION_UP:
	    if (mMode == Mode.PAN) {
		final long now = System.currentTimeMillis();
		if (panAfterPinchTimeout < now) {
		    mVelocityTracker.computeCurrentVelocity(1000, mScaledMaximumFlingVelocity);
		    mZoomControl.startFling(-mVelocityTracker.getXVelocity() / v.getWidth(),
			    -mVelocityTracker.getYVelocity() / v.getHeight());
		} 
	    } else if (mMode != Mode.PINCHZOOM) {
		mZoomControl.startFling(0, 0);
	    } 
	    mVelocityTracker.recycle();
	    mVelocityTracker = null;
	case MotionEvent.ACTION_POINTER_UP:
	    if (event.getPointerCount() > 1 && mMode == Mode.PINCHZOOM) {
		panAfterPinchTimeout = System.currentTimeMillis() + 100;
	    } 
	    mMode = Mode.UNDEFINED;
	    break; 
 
	case MotionEvent.ACTION_MOVE:
	    final float dx = (x - mX) / v.getWidth();
	    final float dy = (y - mY) / v.getHeight();
 
	    if (mMode == Mode.PAN) {
		mZoomControl.pan(-dx, -dy);
	    } else if (mMode == Mode.PINCHZOOM) {
		float newDist = spacing(event);
		if (newDist > 10f) {
		    final float scale = newDist / oldDist;
		    final float xx = mMidPoint.x / v.getWidth();
		    final float yy = mMidPoint.y / v.getHeight();
		    mZoomControl.zoom(scale, xx, yy);
		    oldDist = newDist;
		} 
	    } else { 
		if (mZoomControl.getZoomState().getZoom() == 1.0f) {
		    return true; 
		} 
 
		final float scrollX = mDownX - x;
		final float scrollY = mDownY - y;
 
		final float dist = (float) Math.sqrt(scrollX * scrollX + scrollY * scrollY);
 
		if (dist >= mScaledTouchSlop) {
		    mMode = Mode.PAN;
		} 
	    } 
 
	    mX = x;
	    mY = y;
	    break; 
 
	default: 
	    mVelocityTracker.recycle();
	    mVelocityTracker = null;
	    mMode = Mode.UNDEFINED;
	    break; 
	} 
	return true;