码迷,mamicode.com
首页 > 移动开发 > 详细

【安卓笔记】VelocityTracker使用示例

时间:2014-11-30 14:14:01      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   io   ar   os   使用   sp   java   

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使用示例

标签:android   style   blog   io   ar   os   使用   sp   java   

原文地址:http://blog.csdn.net/chdjj/article/details/41621907

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!