【安卓笔记】VelocityTracker使用示例
来源:程序员人生 发布时间:2014-12-16 08:56:09 阅读次数:3258次
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 = ⑴;
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);
}
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠