首页 > 代码库 > 【安卓笔记】VelocityTracker使用示例
【安卓笔记】VelocityTracker使用示例
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); } }
【安卓笔记】VelocityTracker使用示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。