Android VelocityTracker的介绍

VelocityTracker的介绍:

简单来说就是:X/Y方向的速度相关的帮助类

/**
 * Helper for tracking the velocity of touch events, for implementing flinging and other such gestures. 
 * Use obtain to retrieve a new instance of the class when you are going to begin tracking. 
 * Put the motion events you receive into it with addMovement(MotionEvent). 
 * When you want to determine the velocity call computeCurrentVelocity(int) and then call getXVelocity(int) and getYVelocity(int) to retrieve the velocity for each pointer id.
 */

使用步骤:

  • 声明

      private VelocityTracker mVelocityTracker;
    
  • 初始化

      private void init() {
          mVelocityTracker = VelocityTracker.obtain();
      }
    
  • 在onTouchEvent的开头添加滑动事件

      public boolean onTouchEvent(MotionEvent event) {
          mVelocityTracker.addMovement(event);
          ...
      }
    
  • 在onTouchEvent的MotionEvent.ACTION_UP中使用

      case MotionEvent.ACTION_UP: {
          int scrollX = getScrollX();
          int scrollToChildIndex = scrollX / mChildWidth;
          mVelocityTracker.computeCurrentVelocity(1000);
          float xVelocity = mVelocityTracker.getXVelocity();
          if (Math.abs(xVelocity) >= 50) {
              mChildIndex = xVelocity > 0 ? mChildIndex - 1 : mChildIndex + 1;
          } else {
              mChildIndex = (scrollX + mChildWidth / 2) / mChildWidth;
          }
          mChildIndex = Math.max(0, Math.min(mChildIndex, mChildrenSize - 1));
          int dx = mChildIndex * mChildWidth - scrollX;
          smoothScrollBy(dx, 0);
          mVelocityTracker.clear();
          break;
      }
    
  • 在onDetachedFromWindow中回收

      @Override
      protected void onDetachedFromWindow() {
          mVelocityTracker.recycle();
          super.onDetachedFromWindow();
      }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容