运动事件android的速度或加速度

时间:2012-04-14 17:51:23

标签: android performance touch velocity acceleration

是否可以使用现有的api获取android中触摸事件的速度或速度或加速度?我已经浏览了MotionEvent类,该类中的任何字段似乎都没有检索到我需要的信息。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:14)

在这种情况下,

MotionEvent对您没有帮助。您可以使用VelocityTracker类。它获取MotionEvent实例并计算最近触摸事件的速度。 您可以在这里查看其文档: http://developer.android.com/reference/android/view/VelocityTracker.html

首先,您必须通过gets()方法获取实例:

VelocityTracker velocity = VelocityTracker.obtain();

然后您可以将ACTION_MOVE事件添加到其队列中:

    if(event.getAction() == MotionEvent.ACTION_MOVE)
    {
        velocity.addMovement(event);
    }

然后你可以计算速度并提取x_velocity和y_velocity

velocity.computeCurrentVelocity(1000);
float x_velocity = velocity.getXVelocity();
float y_velocity = velocity.getYVelocity();

我希望它适合你。

答案 1 :(得分:0)

您需要使用System.nanoTime在每两个事件之间手动计算速度。加速的方式相同(但这次使用的是速度而不是坐标)。