Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track the velocity of a moving view

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

like image 497
Bradley Campbell Avatar asked Jul 04 '13 03:07

Bradley Campbell


2 Answers

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.

like image 157
MartinodF Avatar answered Oct 04 '22 18:10

MartinodF


The simplest way deals with absolute coordinates write:

motionEvent.setLocation(e.getRawX(), e.getRawY());

like image 39
Alexey Subbota Avatar answered Oct 04 '22 20:10

Alexey Subbota