如何检测类中触摸事件的速度扩展View?

时间:2014-07-14 11:45:39

标签: android ontouchevent ontouchlistener ondraw

我有一个自定义视图,我想检测触摸及其速度。 目前,我重写onTouchEvent但是如您所知,此方法不提供任何触摸事件的速度。我可以覆盖的任何其他方法为我提供触摸事件的速度吗?

2 个答案:

答案 0 :(得分:0)

试试这段代码

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;}

答案 1 :(得分:0)

答案很好地提供了 here 。触摸开始时获取startX,startY位置,触摸结束时获取endX,endY。

然后你可以计算出移动的长度和时间。

移动长度与制作时间的比例将是你的速度。

修改

以下是建议的跟踪移动速度的方法: Android Docs