0

I have a customised view and I want to detect touches as well as their velocity. currently, I override onTouchEventbut as you know, the velocity of any touch event is not provided by this method. Is the any other method I can override to provide me with the velocity of the touch events?

Amrmsmb
  • 1
  • 27
  • 104
  • 226

2 Answers2

0

try this code

public boolean onTouchEvent(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);

        final int action = event.getAction();
        final float x = event.getX();
        final float y = event.getY();

        switch (action) {
        case MotionEvent.ACTION_DOWN:
            // Log.i(TAG, "on touch down ^^");
            mLastMotionX = x;
            mLastMotionY = y;
            break;

        case MotionEvent.ACTION_MOVE:
            // Log.i(TAG, "on touch move ^^");
            mLastMotionX = x;
            mLastMotionY = y;
            break;

        case MotionEvent.ACTION_UP:
            mLastMotionX = x;
            mLastMotionY = y;
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000);
            int velocityX = (int) velocityTracker.getXVelocity();
            Log.e("Velocity X",""+velocityX );
            int velocityY = (int) velocityTracker.getYVelocity();
            Log.e("Velocity Y",""+velocityY );
            if (mVelocityTracker != null) {
                mVelocityTracker.recycle();
                mVelocityTracker = null;
            }

            break;
        case MotionEvent.ACTION_CANCEL:

            break;
        }

        return true;}
Ravi Kant
  • 820
  • 6
  • 13
0

The answer provided here nicely. Get the startX,startY positions when the touch has been started, and endX,endY when the touch has ended.

Then you can calculate the movement length and time it took to make that movement.

The proportion of the length of the movement and the time it took to make it will be your velocity.

EDIT:

Here's the suggested way of tracking movement velocity: Android Docs

Community
  • 1
  • 1
Simas
  • 43,548
  • 10
  • 88
  • 116