【安卓笔记】VelocityTracker使用示例
1.获取VelocityTracker实例:
VelocityTracker mVelocityTracker = VelocityTracker.obtain();2.将MotionEvent事件纳入到VelocityTracker中:
mVelocityTracker.addMovement(event);3.计算瞬时速度:
mVelocityTracker.computeCurrentVelocity(units,maxVelocity);4.获取xy方向上的速度:
float vX = mVelocityTracker.getXVelocity(pointId); float vY = mVelocityTracker.getYVelocity(pointId);5.回收VelocityTracker:
mVelocityTracker.clear(); mVelocityTracker.recycle();使用示例:
package com.example.velocitytrackerdemo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.ViewConfiguration; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private VelocityTracker mVelocityTracker; private int mMaxFlingVelocity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMaxFlingVelocity = ViewConfiguration.get(this).getScaledMaximumFlingVelocity(); } /** * 获取速度追踪器 * @return */ private VelocityTracker getVelocityTracker() { if(mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } return mVelocityTracker; } /** * 回收速度追踪器 */ private void recycleVelocityTracker() { if(mVelocityTracker != null) { mVelocityTracker.clear(); mVelocityTracker.recycle(); mVelocityTracker = null; } } @Override public boolean onTouchEvent(MotionEvent event) { //1.获取速度追踪器 getVelocityTracker(); //2.将当前事件纳入到追踪器中 mVelocityTracker.addMovement(event); int pointId = -1; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.i(TAG,"ACTION_DOWN"); pointId = event.getPointerId(0); break; case MotionEvent.ACTION_MOVE: Log.i(TAG,"ACTION_MOVE"); //3.计算当前速度 mVelocityTracker.computeCurrentVelocity(1000,mMaxFlingVelocity); //获取x y方向上的速度 float vX = mVelocityTracker.getXVelocity(pointId); float vY = mVelocityTracker.getYVelocity(pointId); Log.i(TAG,"vX = "+vX+",vY = "+vY); break; case MotionEvent.ACTION_UP: Log.i(TAG,"ACTION_UP"); //4.回收速度追踪器 recycleVelocityTracker(); break; default: break; } return super.onTouchEvent(event); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。