I am writing an application with an element like facebook chat head that freely moves on the screen using finger. I'm trying to find out the velocity of the view so that I can decide the final location of the view once the ACTION_UP is called. The problem is that the velocity returned by velocity tracker is correct sometimes but wrong half of the times.
Many times, when I try to throw the chat head to the right, it gives a negative x velocity, which is an erratic behaviour. So I went into the developer settings of the phone and activated the pointer location option. Now on the top of the phone, on the top of status bar, the displayed 'Xv' value is always right, but the printed log of the X velocity measured with androidVelocityTracker is still erratic.
Here's my code:
chatHead.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int rawX = (int) event.getRawX();
int rawY = (int) event.getRawY();
int pointerIndex = 0;
int pointerId = event.getPointerId(pointerIndex);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN
//velocity tracker
if (mTracker == null) {
mTracker = VelocityTracker.obtain();
} else {
mTracker.clear();
}
mTracker.addMovement(event);
return true;
case MotionEvent.ACTION_UP:
Log.d(TAG, "x velocity = " + lastKnownXVelocity);
Log.d(TAG, "y velocity = " + lastKnownYVelocity);
return true;
case MotionEvent.ACTION_MOVE:
//01. add movement to velocity trakcer
mTracker.addMovement(event);
mTracker.computeCurrentVelocity(1000);
lastKnownXVelocity = VelocityTrackerCompat.getXVelocity(mTracker, pointerId);
lastKnownYVelocity = VelocityTrackerCompat.getYVelocity(mTracker, pointerId);
//lastKnownXVelocity = mTracker.getXVelocity(); //have also tried this code...it's shows no different results
//lastKnownYVelocity = mTracker.getYVelocity();
//02. code to drag the circle on pointer move
globalParams.x = paramsX;
globalParams.y = paramsY;
windowManager.updateViewLayout(chatHead, globalParams);
return true;
case MotionEvent.ACTION_CANCEL:
// Return a VelocityTracker object back to be re-used by others.
mTracker.recycle();
break;
}
return false;
}
});
Please let me know if I'm making some mistake or something? Or is there any other way to get the correct velocity.
Thanks in advance!