Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 教學:輕鬆捕獲螢幕雙擊事件

編輯:關於 Android 程式設計

在 Android 遊戲開發中,我們常常需要像 PC 一樣在螢幕上進行雙擊操作。然而,Android 1.6 版本以前並未提供完善的手勢識別類;Android 1.5 的 SDK 雖然有 android.view.GestureDetector.OnDoubleTapListener,但實測卻無法正常工作,原因不明。最終我們採用了下面的解法:

 public class TouchLayout extends RelativeLayout { public Handler doubleTapHandler = null; protected long lastDown = -1; public final static long DOUBLE_TIME = 500; public TouchLayout(Context context) { super(context); } public TouchLayout(Context context, AttributeSet attrs) { super(context, attrs); } public TouchLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public boolean onTouchEvent(MotionEvent event) { this.handleEvent(event); if (event.getAction() == MotionEvent.ACTION_DOWN) { long nowDown = System.currentTimeMillis(); if (nowDown - lastDown < DOUBLE_TIME) { if (doubleTapHandler != null) doubleTapHandler.sendEmptyMessage(-1); } else { lastDown = nowDown; } } return true; } protected void handleEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //Do sth 這裡處理即可 break; case MotionEvent.ACTION_UP: //Do sth break; } } } 

核心思路其實很樸素:每次 ACTION_DOWN 時記錄時間戳,若與上一次按下的間隔小於 500 毫秒(DOUBLE_TIME),就判定為雙擊,並透過 Handler 發送訊息觸發後續處理。這樣一來,即使不使用系統的雙擊手勢類,也能穩定地攔截到螢幕的雙擊行為。

以上就是 Android 螢幕雙擊事件捕獲的示例,後續會繼續補充相關資料,希望能幫助到開發 Android 應用的朋友。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved