我有一个视图,根据触摸移动,我想跟踪我移动它的速度,所以我使用VelocityTracker
,如下所示,但根据我的日志,当我移动时速度有时是负的我的视图从左到右,相反(当我从右向左移动视图时,速度有时是正的),
我不明白为什么。
public boolean onTouch(View v, MotionEvent event) {
int eid = event.getAction();
int index = event.getActionIndex();
int pointerId = event.getPointerId(index);
switch (eid) {
case MotionEvent.ACTION_DOWN:
if (firstTouch)
offsetY = (int) (event.getRawY() - v.getY());
if (firstTouch)
offsetX = (int) (event.getRawX() - v.getX());
if(mVelocityTracker == null)
mVelocityTracker = VelocityTracker.obtain();
else
mVelocityTracker.clear();
mVelocityTracker.addMovement(event);
break;
case MotionEvent.ACTION_MOVE:
mVelocityTracker.addMovement(event);
v.setX(event.getRawX() - offsetX);
break;
case MotionEvent.ACTION_UP:
mVelocityTracker.computeCurrentVelocity(1000);
float velocity= VelocityTrackerCompat.getXVelocity(mVelocityTracker,pointerId);
// I print the speed and get the negative somtimes
Log.d("speed ","speed : "+speed );
firstTouch = true;
mVelocityTracker.recycle();
mVelocityTracker = null;
break;
default:
break;
}
return true;
}
});
任何人都知道为什么会发生这种情况以及如何解决它? 谢谢!