本課程將說明如何追蹤觸控事件中的動作。
每當目前的觸控聯絡人位置、壓力或大小有所變更,系統就會透過 ACTION_MOVE
事件觸發新的 onTouchEvent()
。如「偵測常用手勢」一節所述,所有事件都會記錄在 onTouchEvent()
的 MotionEvent
參數中。
由於手指觸控事件不一定是最精確的互動形式,因此偵測觸控事件的頻率通常會比單純接觸方式更大。為協助應用程式區分以動作為基礎的手勢 (例如滑動) 和非移動手勢 (例如一次輕觸),Android 納入了「觸控圈」的概念。觸控偏移是指使用者觸控移動的距離 (以像素為單位),在將手勢解讀為以動作為基礎的手勢前。如要進一步瞭解這個主題,請參閱「管理 ViewGroup 中的觸控事件」。
視應用程式的需求而定,有幾種方式可以追蹤手勢中的動作。範例如下:
- 指標的起始和結束位置,例如將螢幕上的物件從 A 點移動到 B 點。
- 指標的移動方向,由 X 和 Y 座標決定。
- 。如要查看手勢記錄的大小,請呼叫
MotionEvent
方法getHistorySize()
。然後,您就可以使用動作事件的getHistorical<Value>
方法,取得每個歷史事件的位置、大小、時間和壓力。轉譯使用者手指軌跡時 (例如用於觸控繪圖),歷史記錄會很實用。詳情請參閱MotionEvent
參考資料。 - 指標在觸控螢幕上移動時的速率。
請參閱下列相關資源:
追蹤速度
就可以根據指標移動的距離或方向,使用以動作為基礎的手勢。不過,速率通常是追蹤手勢的特性或決定手勢是否發生的因素。為簡化速度計算程序,Android 提供 VelocityTracker
類別。VelocityTracker
可協助您追蹤觸控事件的速率。如果手勢屬於手勢操作條件 (例如快速滑過),這項功能就能派上用場。
以下範例說明 VelocityTracker
API 中方法的用途:
Kotlin
private const val DEBUG_TAG = "Velocity" class MainActivity : Activity() { private var mVelocityTracker: VelocityTracker? = null override fun onTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { // Reset the velocity tracker back to its initial state. mVelocityTracker?.clear() // If necessary, retrieve a new VelocityTracker object to watch // the velocity of a motion. mVelocityTracker = mVelocityTracker ?: VelocityTracker.obtain() // Add a user's movement to the tracker. mVelocityTracker?.addMovement(event) } MotionEvent.ACTION_MOVE -> { mVelocityTracker?.apply { val pointerId: Int = event.getPointerId(event.actionIndex) addMovement(event) // When you want to determine the velocity, call // computeCurrentVelocity(). Then, call getXVelocity() and // getYVelocity() to retrieve the velocity for each pointer // ID. computeCurrentVelocity(1000) // Log velocity of pixels per second. It's best practice to // use VelocityTrackerCompat where possible. Log.d("", "X velocity: ${getXVelocity(pointerId)}") Log.d("", "Y velocity: ${getYVelocity(pointerId)}") } } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { // Return a VelocityTracker object back to be re-used by others. mVelocityTracker?.recycle() mVelocityTracker = null } } return true } }
Java
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. It's best practice to use // VelocityTrackerCompat where possible. Log.d("", "X velocity: " + mVelocityTracker.getXVelocity(pointerId)); Log.d("", "Y velocity: " + mVelocityTracker.getYVelocity(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; } }
使用指標擷取功能
部分應用程式 (例如遊戲、遠端桌面和虛擬化用戶端) 更容易控制滑鼠遊標。指標擷取是 Android 8.0 (API 級別 26) 以上版本提供的功能,可將所有滑鼠事件傳送至應用程式中的焦點檢視畫面,藉此提供這個控制項。
要求擷取指標
只有在含有焦點的檢視區塊階層有焦點時,應用程式中的檢視區塊才能要求擷取指標。因此,要求指標會在檢視畫面發生特定的使用者動作時擷取,例如在 onClick()
事件或活動的 onWindowFocusChanged()
事件處理常式中。
如要要求擷取指標,請對檢視畫面呼叫 requestPointerCapture()
方法。以下程式碼範例說明如何在使用者點選檢視畫面時要求指標擷取:
Kotlin
fun onClick(view: View) { view.requestPointerCapture() }
Java
@Override public void onClick(View view) { view.requestPointerCapture(); }
成功擷取指標的要求後,Android 會呼叫 onPointerCaptureChange(true)
。系統會將滑鼠事件傳送至應用程式中的聚焦檢視畫面,前提是其所在的檢視區塊階層必須與要求擷取的檢視區塊相同。在擷取發布之前,其他應用程式會停止接收滑鼠事件,包括 ACTION_OUTSIDE
事件。Android 會正常傳送滑鼠以外的指標事件,但不再顯示滑鼠遊標。
處理擷取的指標事件
當檢視畫面成功取得指標擷取內容後,Android 就會傳送滑鼠事件。焦點檢視可以執行下列任一工作來處理事件:
- 如果使用自訂檢視畫面,請覆寫
onCapturedPointerEvent(MotionEvent)
。 - 否則,請註冊
OnCapturedPointerListener
。
以下程式碼範例說明如何實作 onCapturedPointerEvent(MotionEvent)
:
Kotlin
override fun onCapturedPointerEvent(motionEvent: MotionEvent): Boolean { // Get the coordinates required by your app. val verticalOffset: Float = motionEvent.y // Use the coordinates to update your view and return true if the event is // successfully processed. return true }
Java
@Override public boolean onCapturedPointerEvent(MotionEvent motionEvent) { // Get the coordinates required by your app. float verticalOffset = motionEvent.getY(); // Use the coordinates to update your view and return true if the event is // successfully processed. return true; }
以下程式碼範例說明如何註冊 OnCapturedPointerListener
:
Kotlin
myView.setOnCapturedPointerListener { view, motionEvent -> // Get the coordinates required by your app. val horizontalOffset: Float = motionEvent.x // Use the coordinates to update your view and return true if the event is // successfully processed. true }
Java
myView.setOnCapturedPointerListener(new View.OnCapturedPointerListener() { @Override public boolean onCapturedPointer (View view, MotionEvent motionEvent) { // Get the coordinates required by your app. float horizontalOffset = motionEvent.getX(); // Use the coordinates to update your view and return true if the event is // successfully processed. return true; } });
無論使用的是自訂檢視畫面或註冊事件監聽器,檢視畫面都會收到 MotionEvent
,其中包含指定相對移動 (例如 X 或 Y 差異值) 的指標座標,與軌跡球裝置傳遞的座標類似。您可以使用 getX()
和 getY()
擷取座標。
放開指標擷取
應用程式中的檢視畫面可以呼叫 releasePointerCapture()
來釋出指標擷取內容,如以下程式碼範例所示:
Kotlin
override fun onClick(view: View) { view.releasePointerCapture() }
Java
@Override public void onClick(View view) { view.releasePointerCapture(); }
系統可以在您未明確呼叫 releasePointerCapture()
的情況下擷取檢視畫面,這通常是因為要求擷取的檢視區塊階層失去焦點。