I'm running into issues when using the VelocityTracker class. Velocity tracking seems to work very well if you are measuring the velocity of touch events on a non-moving view, but as soon as the view starts moving with your finger (using using translateY/X or setY/X), the velocity is completely random (I think the velocity is calculated using the view's position?). Does anyone have any suggestions for getting an accurate velocity of your movement when swiping a view?
Notes: I am using the touch events from my View's onTouchListener for Velocity tracking.
Cheers
You should keep track of how much the view has been moved and call MotionEvent.offsetLocation
to "fix" the event coordinates before passing it to a VelocityTracker
.
private float mLastX;
private float mTranslationX;
private VelocityTracker mTracker;
@Override
public boolean onTouch(final View view, MotionEvent motionEvent) {
motionEvent.offsetLocation(mTranslationX, 0);
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mLastX = motionEvent.getRawX();
mTracker = VelocityTracker.obtain();
mTracker.addMovement(motionEvent);
return true;
case MotionEvent.ACTION_MOVE:
mTranslationX += motionEvent.getRawX() - mLastX;
view.setTranslationX(mTranslationX);
mTracker.addMovement(motionEvent);
return true;
case MotionEvent.ACTION_UP:
// get your correct velocity from mTracker
...
}
}
Check out the documentation for MotionEvent.getRawX
/ Y
too.
They return the X/Y coordinates of the pointer relative to the entire screen, therefore they aren't affected by the movement of whatever View you're listening on.
The simplest way deals with absolute coordinates write:
motionEvent.setLocation(e.getRawX(), e.getRawY());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With