使用者使用觸控筆繪圖、書寫或與應用程式互動時,有時手掌會碰到螢幕。在系統將這類事件辨別為手掌誤觸,並加以忽略之前,可能就會先將觸控事件回報給您的應用程式。
辨識並忽略手掌觸碰
您的應用程式必須辨識並忽略不必要的觸控事件。藉由將 MotionEvent
物件調度至應用程式,Android 會取消手掌觸控事件。
檢查調度給應用程式的
MotionEvent
物件。請使用MotionEvent
API 判斷事件屬性 (動作和標記):- 單指標事件 - 檢查
ACTION_CANCEL
。如果是 Android 13 以上版本,請一併檢查FLAG_CANCELED
。 - 多指標事件 - 在 Android 13 以上版本中,檢查
ACTION_POINTER_UP
和FLAG_CANCELED
。
- 單指標事件 - 檢查
忽略具有
ACTION_CANCEL
和ACTION_POINTER_UP
/FLAG_CANCELED
屬性的動作事件。
1. 取得動作事件物件
在應用程式中新增 OnTouchListener
:
Kotlin
val myView = findViewById<View>(R.id.myView).apply { setOnTouchListener { view, event -> // Process motion event. } }
Java
View myView = findViewById(R.id.myView); myView.setOnTouchListener( (view, event) -> { // Process motion event. });
2. 判斷事件動作和標記
檢查是否有 ACTION_CANCEL
,這表示所有 API 級別上的單指標事件。如果是 Android 13 以上版本,請檢查 ACTION_POINTER_UP
是否有 FLAG_CANCELED.
。
Kotlin
val myView = findViewById<View>(R.id.myView).apply { setOnTouchListener { view, event -> when (event.actionMasked) { MotionEvent.ACTION_CANCEL -> { //Process canceled single-pointer motion event for all SDK versions. } MotionEvent.ACTION_POINTER_UP -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && (event.flags and MotionEvent.FLAG_CANCELED) == MotionEvent.FLAG_CANCELED) { //Process canceled multi-pointer motion event for Android 13 and higher. } } } true } }
Java
View myView = findViewById(R.id.myView); myView.setOnTouchListener( (view, event) -> { switch (event.getActionMasked()) { case MotionEvent.ACTION_CANCEL: // Process canceled single-pointer motion event for all SDK versions. case MotionEvent.ACTION_UP: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && (event.getFlags() & MotionEvent.FLAG_CANCELED) == MotionEvent.FLAG_CANCELED) { //Process canceled multi-pointer motion event for Android 13 and higher. } } return true; });
3. 取消手勢
辨識出手掌觸碰事件後,您可以取消手勢在螢幕上引發的操作。
您的應用程式必須保留使用者動作記錄,以便在有手掌觸碰這類情形發生時,取消這些無意的輸入操作。如需維護記錄的範例,請參閱「強化 Android 應用程式中的觸控筆支援」程式碼研究室中的「實作基本繪圖應用程式」。
重點
MotionEvent
:代表觸控和動作事件,包含判斷是否應忽略事件所需的資訊。OnTouchListener#onTouch()
:接收MotionEvent
物件。MotionEvent#getActionMasked()
:傳回與動作事件相關聯的動作。ACTION_CANCEL
:MotionEvent
常數,表示應取消手勢。ACTION_POINTER_UP
:MotionEvent
常數,表示第一個指標以外的指標已上移 (也就是已放棄與裝置螢幕接觸)。FLAG_CANCELED
:MotionEvent
常數,表示指標上移是無意間的觸控事件所致。已在 Android 13 (API 級別 33) 以上版本的ACTION_POINTER_UP
和ACTION_CANCEL
事件中加入此事件。
結果
您的應用程式現在可以辨別並拒絕多指標事件 (在 Android 13 以上的 API 級別上) 和單指標事件 (在所有 API 級別上) 的手掌觸碰操作了。
包含此指南的集合
本指南是精選的快速指南系列之一,涵蓋更廣泛的 Android 開發目標:
![](https://developer.android.google.cn/static/images/quick-guides/collection-illustration.png?hl=zh-tw)
針對大螢幕進行最佳化
讓應用程式支援平板電腦、折疊式裝置和 ChromeOS 裝置的最佳使用者體驗。
有問題或意見回饋嗎?
請前往常見問題頁面,瞭解快速指南或與我們聯絡,分享您的想法。