package com.example.velocitytracke;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv;
private VelocityTracker tracker;
private int mPointerId;
private int mMaxVelocity;
private static final String sFormatStr = "velocityX=%f\nvelocityY=%f";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
// http://www.cnblogs.com/supersugar/archive/2012/08/08/2628602.html
mMaxVelocity = ViewConfiguration.get(this)
.getScaledMaximumFlingVelocity();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
acquireVelocityTracker(event);
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mPointerId = event.getPointerId(0); // 求第一个触点的id, 此时可能有多个触点,但至少一个
break;
case MotionEvent.ACTION_MOVE:
// 求伪瞬时速度
tracker.computeCurrentVelocity(1000, mMaxVelocity);
final float velocityX = tracker.getXVelocity(mPointerId);
final float velocityY = tracker.getYVelocity(mPointerId);
recodeInfo(velocityX, velocityY);
break;
case MotionEvent.ACTION_UP:
releaseVelocityTracker();
default:
releaseVelocityTracker();
break;
}
return super.onTouchEvent(event);
}
/**
* 释放VelocityTracker
*
* @see android.view.VelocityTracker#clear()
* @see android.view.VelocityTracker#recycle()
*/
private void releaseVelocityTracker() {
if (null != tracker) {
tracker.clear();
tracker.recycle();
tracker = null;
}
}
/**
* 记录当前速度
*
* @param velocityX
* x轴速度
* @param velocityY
* y轴速度
*/
private void recodeInfo(final float velocityX, final float velocityY) {
final String info = String.format(sFormatStr, velocityX, velocityY);
tv.setText(info);
}
private void acquireVelocityTracker(MotionEvent event) {
if (null == tracker) {
tracker = VelocityTracker.obtain();
}
tracker.addMovement(event);
}
}
android VelocityTracke 获取x轴 y轴 的速度
最新推荐文章于 2023-05-31 23:00:50 发布