Created
May 13, 2016 11:22
-
-
Save CoenQian/bfeefc595de11dfce8049662880bca2e to your computer and use it in GitHub Desktop.
sample for VelocityTracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class VelocityView extends View { | |
public static final String TAG = "VelocityView"; | |
private VelocityTracker mVelocityTracker; | |
public VelocityView(Context context) { | |
super(context); | |
} | |
public VelocityView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
@Override | |
public boolean onTouchEvent(MotionEvent event) { | |
obtainVelocityTracker(event); | |
switch (event.getAction()) { | |
case MotionEvent.ACTION_UP: | |
final VelocityTracker velocityTracker = mVelocityTracker; | |
velocityTracker.computeCurrentVelocity(1000); | |
float xVelocity = mVelocityTracker.getXVelocity(); | |
float yVelocity = mVelocityTracker.getYVelocity(); | |
Log.i(TAG, "xVelocity: " + xVelocity + ", yVelocity: " + yVelocity); | |
mVelocityTracker.clear(); | |
break; | |
default: | |
break; | |
} | |
return true; | |
} | |
private void obtainVelocityTracker(MotionEvent event) { | |
if (mVelocityTracker == null) { | |
mVelocityTracker = VelocityTracker.obtain(); | |
} | |
mVelocityTracker.addMovement(event); | |
} | |
private void releaseVelocityTracker() { | |
if (mVelocityTracker != null) { | |
mVelocityTracker.recycle(); | |
mVelocityTracker = null; | |
} | |
} | |
@Override | |
protected void onDetachedFromWindow() { | |
super.onDetachedFromWindow(); | |
releaseVelocityTracker(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment