https://developer.android.com/training/gestures/movement.html
跟蹤移動(Tracking Movement)
當觸摸點位置,壓力或尺寸發(fā)生變化時,會觸發(fā)一個新的 MotionEvent.ACTION_MOVE 事件。
因為基于手指的觸摸并不總是最精確的交互形式,因此檢測觸摸事件通常更多地基于移動而不是簡單的接觸。 為了幫助應(yīng)用程序區(qū)分基于移動的手勢(例如swipe)和非移動手勢(例如single tap),Android包括“touch slop”的概念。 “touch slop”是指用戶的觸摸可以在手勢被解釋為基于運動的手勢之前漫游的距離(以像素為單位)。 有關(guān)此主題的更多討論,請參閱管理ViewGroup中的觸摸事件。
根據(jù)您的應(yīng)用需求,有幾種不同的方式來跟蹤手勢中的移動。 例如:
- 指針的開始和結(jié)束位置(例如,將屏幕對象從點A移動到點B)。
- 指針正在行進的方向,由x和y坐標確定。
- 手勢歷史。
通過調(diào)用MotionEvent方法getHistorySize()可以得到手勢歷史的大小。
然后,可以使用MotionEvent的getHistorical<Value>方法獲取每個歷史事件的位置,大小,時間和壓力。 渲染用戶手指的蹤跡(例如觸摸繪圖)時,歷史記錄非常有用。 有關(guān)詳細信息,請參閱MotionEvent參考。 - 指針在觸摸屏上移動時的速度。
跟蹤速度(Track Velocity)
你可以有一個基于運動的手勢,它只是基于指針行進的 距離 和/或 方向。
但速度通常是跟蹤手勢特征或甚至決定手勢是否發(fā)生的決定性因素。 為了使速度計算更容易,Android在支持庫中提供VelocityTracker類和VelocityTrackerCompat類。
VelocityTracker可以幫助您跟蹤觸摸事件的速度。
這對于速度是手勢的標準的一部分的手勢(例如fling)是有用的。
以下是一個簡單的示例,說明VelocityTracker API中方法的用途:
public class MainActivity extends Activity {
private static final String DEBUG_TAG = "Velocity";
...
private VelocityTracker mVelocityTracker = null;
@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.
Log.d("", "X velocity: " + VelocityTrackerCompat.getXVelocity(mVelocityTracker, pointerId));
Log.d("", "Y velocity: " + VelocityTrackerCompat.getYVelocity(mVelocityTracker, pointerId));
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// Return a VelocityTracker object back to be re-used by others.
mVelocityTracker.recycle();
break;
}
return true;
}
}
注意:在ACTION_UP之后,X和Y速度將為0,您應(yīng)該在ACTION_MOVE事件之后計算速度。