这应该是一件非常简单的事情。用户将手指放在屏幕上并在屏幕上拖动。 onTouch 触发了两个事件:
- MotionEvent.ACTION_DOWN
- MotionEvent.ACTION_MOVE
现在,我如何计算 ACTION_MOVE 手势的速度?用户在手势过程中手指拖得更慢或更快,所以我想我需要计算两个中间触摸点之间的速度:lastTouchedPointX,lastTouchedPointY 和 event.getX(),event.getY()。
以前有人做过吗?
最佳答案
您所需要的可以通过使用标准 VelocityTracker
来实现类(class)。更多关于谷歌用户输入最佳实践的详细信息,同时跟踪移动here .下面的大部分代码(通过在 X 和 Y 轴上显示每个抛掷/移动的速度来演示 VelocityTracker
的使用)取自之前的资源链接:
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.VelocityTrackerCompat;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.widget.TextView;
public class MainActivity extends Activity {
private VelocityTracker mVelocityTracker = null;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
mTextView.setText("Move finger on screen to get velocity.");
setContentView(mTextView);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int index = event.getActionIndex();
int action = event.getActionMasked();
int pointerId = event.getPointerId(index);
switch (action) {
case MotionEvent.ACTION_DOWN:
if (mVelocityTracker == null) {
// Retrieve a new VelocityTracker object to watch the velocity
// of a motion.
mVelocityTracker = VelocityTracker.obtain();
} else {
// Reset the velocity tracker back to its initial state.
mVelocityTracker.clear();
}
// Add a user's movement to the tracker.
mVelocityTracker.addMovement(event);
break;
case MotionEvent.ACTION_MOVE:
mVelocityTracker.addMovement(event);
// When you want to determine the velocity, call
// computeCurrentVelocity(). Then call getXVelocity()
// and getYVelocity() to retrieve the velocity for each pointer ID.
mVelocityTracker.computeCurrentVelocity(1000);
// Log velocity of pixels per second
// Best practice to use VelocityTrackerCompat where possible.
mTextView.setText("X velocity: "
+ VelocityTrackerCompat.getXVelocity(mVelocityTracker,
pointerId)
+ "\nY velocity: "
+ VelocityTrackerCompat.getYVelocity(mVelocityTracker,
pointerId));
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
// Return a VelocityTracker object back to be re-used by others.
mVelocityTracker.recycle();
break;
}
return true;
}
}
关于android - 在 Android 中获取 onTouch ACTION_MOVE 事件的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5815975/