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

Android 4.4 GestureDetector 手勢識別源碼解析

編輯:關於 Android 程式設計

當應用需要處理比較複雜的手勢組合(雙擊、長按、快速滑動等)時,自己從 MotionEvent 一路判斷會很痛苦,這時就該請出 GestureDetector。

使用三步驟

1、實作 OnGestureListener,或繼承 SimpleOnGestureListener 再改寫需要的回呼;

2、建立 GestureDetector 物件,把第一步的監聽器傳入;

3、在 Activity / View 的 onTouchEvent 中呼叫 gestureDetector.onTouchEvent(event)。

所有自訂的手勢判斷邏輯都寫在監聽類裡。

第一步:看建構子

public GestureDetector(Context context, OnGestureListener listener, Handler handler) {
    if (handler != null) {
        mHandler = new GestureHandler(handler);
    } else {
        mHandler = new GestureHandler();
    }
    mListener = listener;
    if (listener instanceof OnDoubleTapListener) {
        setOnDoubleTapListener((OnDoubleTapListener) listener);
    }
    init(context);
}

可以看出 GestureDetector 一定要一個 OnGestureListener,它被存進 mListener。如果傳進來的物件同時實作了 OnDoubleTapListener(繼承 SimpleOnGestureListener 就會是這種情況),還會順便完成雙擊監聽的註冊。init() 負責一些初始設定,這裡先跳過。

第二步:onTouchEvent 開頭的準備工作

public boolean onTouchEvent(MotionEvent ev) {
    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(ev, 0);
    }
    final int action = ev.getAction();
    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(ev);

    final boolean pointerUp =
            (action & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP;
    final int skipIndex = pointerUp ? ev.getActionIndex() : -1;

    // 計算焦點(多點時取平均)
    float sumX = 0, sumY = 0;
    final int count = ev.getPointerCount();
    for (int i = 0; i < count; i++) {
        if (skipIndex == i) continue;
        sumX += ev.getX(i);
        sumY += ev.getY(i);
    }
    final int div = pointerUp ? count - 1 : count;
    final float focusX = sumX / div;
    final float focusY = sumY / div;

    boolean handled = false;
    ...

InputEventConsistencyVerifier 是除錯輔助;mVelocityTracker 是速度追蹤器,後續判斷 fling 要用;接著這段在算事件焦點。單指操作時 getPointerCount() 恆為 1,焦點就是那個點本身。

第三步:核心的 action 分派

switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_POINTER_DOWN:
        mDownFocusX = mLastFocusX = focusX;
        mDownFocusY = mLastFocusY = focusY;
        // 多了一隻手指,取消長按與點擊的計時
        cancelTaps();
        break;

    case MotionEvent.ACTION_POINTER_UP:
        mDownFocusX = mLastFocusX = focusX;
        mDownFocusY = mLastFocusY = focusY;
        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);
        final int upIndex = ev.getActionIndex();
        final int id1 = ev.getPointerId(upIndex);
        final float x1 = mVelocityTracker.getXVelocity(id1);
        final float y1 = mVelocityTracker.getYVelocity(id1);
        // 若離開的手指與其他手指速度方向相反,清掉速度紀錄
        for (int i = 0; i < count; i++) {
            if (i == upIndex) continue;
            final int id2 = ev.getPointerId(i);
            final float x = x1 * mVelocityTracker.getXVelocity(id2);
            final float y = y1 * mVelocityTracker.getYVelocity(id2);
            if (x + y < 0) {
                mVelocityTracker.clear();
                break;
            }
        }
        break;

    case MotionEvent.ACTION_DOWN:
        if (mDoubleTapListener != null) {
            boolean hadTapMessage = mHandler.hasMessages(TAP);
            if (hadTapMessage) mHandler.removeMessages(TAP);
            if ((mCurrentDownEvent != null) && (mPreviousUpEvent != null)
                    && hadTapMessage
                    && isConsideredDoubleTap(mCurrentDownEvent, mPreviousUpEvent, ev)) {
                // 第二次點擊 → 雙擊
                mIsDoubleTapping = true;
                handled |= mDoubleTapListener.onDoubleTap(mCurrentDownEvent);
                handled |= mDoubleTapListener.onDoubleTapEvent(ev);
            } else {
                // 第一次點擊 → 先掛一個延遲訊息等著
                mHandler.sendEmptyMessageDelayed(TAP, DOUBLE_TAP_TIMEOUT);
            }
        }
        mDownFocusX = mLastFocusX = focusX;
        mDownFocusY = mLastFocusY = focusY;
        if (mCurrentDownEvent != null) {
            mCurrentDownEvent.recycle();
        }
        mCurrentDownEvent = MotionEvent.obtain(ev);
        mAlwaysInTapRegion = true;
        mAlwaysInBiggerTapRegion = true;
        mStillDown = true;
        mInLongPress = false;
        mDeferConfirmSingleTap = false;
        if (mIsLongpressEnabled) {
            mHandler.removeMessages(LONG_PRESS);
            mHandler.sendEmptyMessageAtTime(LONG_PRESS,
                    mCurrentDownEvent.getDownTime() + TAP_TIMEOUT + LONGPRESS_TIMEOUT);
        }
        mHandler.sendEmptyMessageAtTime(SHOW_PRESS,
                mCurrentDownEvent.getDownTime() + TAP_TIMEOUT);
        handled |= mListener.onDown(ev);
        break;
    ...
}

各事件對應的回呼

ACTION_DOWN:呼叫 mListener.onDown(ev),同時掛上兩個計時器——SHOW_PRESS(按壓回饋)與 LONG_PRESS(長按)。

ACTION_MOVE:呼叫 mListener.onScroll(mCurrentDownEvent, ev, scrollX, scrollY)。其中 mCurrentDownEvent 是本次手勢的按下點,ev 是當前點,scrollX/Y 是與上一個點的位移差。

ACTION_UP:依判定結果呼叫 mListener.onSingleTapUp(ev) 或 mListener.onFling(mCurrentDownEvent, ev, velocityX, velocityY)。

整套設計的精髓與前面 Handler 那篇一致:用延遲訊息把「短暫事件」壓後確認,等到逾時仍未被打斷才真正觸發單擊,中途來了新事件就撤銷訊息改走高階手勢。理解這一點, GestureDetector 剩下的程式碼就只是細節堆疊了。

未完待續。

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