Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 多點手勢識別

Android 多點手勢識別

編輯:關於Android編程

google 提供的API中,有個類,大家都很熟悉,GestureDetector。使用它,我們可以識別用戶通常會用的手勢。但是,這個類不支持多點觸摸(可能 google認為沒有人會在幾個手指都在屏幕上的時候,使用手勢吧~),不過,最近和朋友們一起做的一個App,的確用到了多點手勢(主要是 onScroll和onFling兩個手勢),所以,我就把這個類拓展了一下,來實現讓多個控件各自跟著一跟手指實現拖動和滑動的效果。    順便說一下,大家應該都知道,在Android3.0以後,Android的觸摸事件的分配機制和以前的版本是有區別的。從3.0開始,用戶在不同控件上操作產生的touch消息不會相互干擾,touch消息會被分派到不同控件上的touchListener中處理。而  在以前的版本中,所有的touch消息,都會被分排到第一個碰到屏幕的手指所操作的控件的touchListener中處理,也就是說,會出現這樣一個矛盾的現象:    在界面上有A,B,C三個控件,然後,當你先用食指按住A,跟著又用中指和無名指(嘛,別的手指也行,不用在意中指還是無名指)按住B,C。當中指和無名指移動的時候,B和C都無法接收到這個ACTION_MOVE消息,而接收到消息的卻是A。而在3.0以上版本中,並不存在這個問題。    使用以下的這個類,可以實現從2.2到3.2平台上手勢識別的兼容。   代碼區:
package com.finger.utils;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
public class MultiTouchGestureDetector {
    @SuppressWarnings("unused")
    private static final String MYTAG = "Ray";
    public static final String CLASS_NAME = "MultiTouchGestureDetector";
    /**
     * 事件信息類 <br/>
     * 用來記錄一個手勢
     */
    private class EventInfo {
        private MultiMotionEvent mCurrentDownEvent;    //當前的down事件
        private MultiMotionEvent mPreviousUpEvent;    //上一次up事件
        private boolean mStillDown;                    //當前手指是否還在屏幕上
        private boolean mInLongPress;                //當前事件是否屬於長按手勢
        private boolean mAlwaysInTapRegion;            //是否當前手指僅在小范圍內移動,當手指僅在小范圍內移動時,視為手指未曾移動過,不會觸發onScroll手勢
        private boolean mAlwaysInBiggerTapRegion;    //是否當前手指在較大范圍內移動,僅當此值為true時,雙擊手勢才能成立
        private boolean mIsDoubleTapping;            //當前手勢,是否為雙擊手勢
        private float mLastMotionY;                    //最後一次事件的X坐標
        private float mLastMotionX;                    //最後一次事件的Y坐標
        private EventInfo(MotionEvent e) {
            this(new MultiMotionEvent(e));
        }
        private EventInfo(MultiMotionEvent me) {
            mCurrentDownEvent = me;
            mStillDown = true;
            mInLongPress = false;
            mAlwaysInTapRegion = true;
            mAlwaysInBiggerTapRegion = true;
            mIsDoubleTapping = false;
        }
        //釋放MotionEven對象,使系統能夠繼續使用它們
        public void recycle() {
            if (mCurrentDownEvent != null) {
                mCurrentDownEvent.recycle();
                mCurrentDownEvent = null;
            }
            if (mPreviousUpEvent != null) {
                mPreviousUpEvent.recycle();
                mPreviousUpEvent = null;
            }
        }
        @Override
        public void finalize() {
            this.recycle();
        }
    }
    /**
     * 多點事件類 <br/>
     * 將一個多點事件拆分為多個單點事件,並方便獲得事件的絕對坐標
     * <br/> 絕對坐標用以在界面中找到觸點所在的控件
     * @author ray-ni
     */
    public class MultiMotionEvent {
        private MotionEvent mEvent;
        private int mIndex;
        private MultiMotionEvent(MotionEvent e) {
            mEvent = e;
            mIndex = (e.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;  //等效於 mEvent.getActionIndex();
        }
        private MultiMotionEvent(MotionEvent e, int idx) {
            mEvent = e;
            mIndex = idx;
        }
        // 行為
        public int getAction() {
            int action = mEvent.getAction() & MotionEvent.ACTION_MASK;    //等效於 mEvent.getActionMasked();
            switch (action) {
            case MotionEvent.ACTION_POINTER_DOWN:
                action = MotionEvent.ACTION_DOWN;
                break;
            case MotionEvent.ACTION_POINTER_UP:
                action = MotionEvent.ACTION_UP;
                break;
            }
            return action;
        }
        // 返回X的絕對坐標
        public float getX() {
            return mEvent.getX(mIndex) + mEvent.getRawX() - mEvent.getX();
        }
        // 返回Y的絕對坐標
        public float getY() {
            return mEvent.getY(mIndex) + mEvent.getRawY() - mEvent.getY();
        }
        // 事件發生的時間
        public long getEventTime() {
            return mEvent.getEventTime();
        }
        // 事件序號
        public int getIndex() {
            return mIndex;
        }
    
        // 事件ID
        public int getId() {
            return mEvent.getPointerId(mIndex);
        }
       
        // 釋放事件對象,使系統能夠繼續使用
        public void recycle() {
            if (mEvent != null) {
                mEvent.recycle();
                mEvent = null;
            }
        }
    }
    // 多點手勢監聽器
    public interface MultiTouchGestureListener {
        // 手指觸碰到屏幕,由一個 ACTION_DOWN觸發
        boolean onDown(MultiMotionEvent e);
        // 確定一個press事件,強調手指按下的一段時間(TAP_TIMEOUT)內,手指未曾移動或抬起
        void onShowPress(MultiMotionEvent e);
        // 手指點擊屏幕後離開,由 ACTION_UP引發,可以簡單的理解為單擊事件,即手指點擊時間不長(未構成長按事件),也不曾移動過
        boolean onSingleTapUp(MultiMotionEvent e);
        // 長按,手指點下後一段時間(DOUBLE_TAP_TIMEOUT)內,不曾抬起或移動
        void onLongPress(MultiMotionEvent e);
        // 拖動,由ACTION_MOVE觸發,手指地按下後,在屏幕上移動
        boolean onScroll(MultiMotionEvent e1, MultiMotionEvent e2, float distanceX, float distanceY);
        // 滑動,由ACTION_UP觸發,手指按下並移動一段距離後,抬起時觸發
        boolean onFling(MultiMotionEvent e1, MultiMotionEvent e2, float velocityX, float velocityY);
    }
    // 多點雙擊監聽器
    public interface MultiTouchDoubleTapListener {
        // 單擊事件確認,強調第一個單擊事件發生後,一段時間內,未發生第二次單擊事件,即確定不會觸發雙擊事件
        boolean onSingleTapConfirmed(MultiMotionEvent e);
        // 雙擊事件, 由ACTION_DOWN觸發,從第一次單擊事件的DOWN事件開始的一段時間(DOUBLE_TAP_TIMEOUT)內結束(即手指),
        // 並且在第一次單擊事件的UP時間開始後的一段時間內(DOUBLE_TAP_TIMEOUT)發生第二次單擊事件,
        // 除此之外兩者坐標間距小於定值(DOUBLE_TAP_SLAP)時,則觸發雙擊事件
        boolean onDoubleTap(MultiMotionEvent e);
        // 雙擊事件,與onDoubleTap事件不同之處在於,構成雙擊的第二次點擊的ACTION_DOWN,ACTION_MOVE和ACTION_UP都會觸發該事件
        boolean onDoubleTapEvent(MultiMotionEvent e);
    }
    // 事件信息隊列,隊列的下標與MotionEvent的pointId對應
    private static List<EventInfo> sEventInfos = new ArrayList<EventInfo>(10);
    // 雙擊判斷隊列,這個隊列中的元素等待雙擊超時的判斷結果
    private static List<EventInfo> sEventForDoubleTap = new ArrayList<EventInfo>(5);
    // 指定大點擊區域的大小(這個比較拗口),這個值主要用於幫助判斷雙擊是否成立
    private int mBiggerTouchSlopSquare = 20 * 20;
    // 判斷是否構成onScroll手勢,當手指在這個范圍內移動時,不觸發onScroll手勢
    private int mTouchSlopSquare;
    // 判斷是否構成雙擊,只有兩次點擊的距離小於該值,才能構成雙擊手勢
    private int mDoubleTapSlopSquare;
    // 最小滑動速度
    private int mMinimumFlingVelocity;
    // 最大滑動速度
    private int mMaximumFlingVelocity;

    // 長按閥值,當手指按下後,在該閥值的時間內,未移動超過mTouchSlopSquare的距離並未抬起,則長按手勢觸發
    private static final int LONGPRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout();
    // showPress手勢的觸發閥值,當手指按下後,在該閥值的時間內,未移動超過mTouchSlopSquare的距離並未抬起,則showPress手勢觸發
    private static final int TAP_TIMEOUT = ViewConfiguration.getTapTimeout();
    // 雙擊超時閥值,僅在兩次雙擊事件的間隔(第一次單擊的UP事件和第二次單擊的DOWN事件)小於此閥值,雙擊事件才能成立
    private static final int DOUBLE_TAP_TIMEOUT = ViewConfiguration.getDoubleTapTimeout();
    // 雙擊區域閥值,僅在兩次雙擊事件的距離小於此閥值,雙擊事件才能成立
    private static final int DOUBLE_TAP_SLAP = 64;

    // GestureHandler所處理的Message的what屬性可能為以下 常量:
    // showPress手勢
    private static final int SHOW_PRESS = 1;
    // 長按手勢
    private static final int LONG_PRESS = 2;
    // SingleTapConfirmed手勢
    private static final int TAP_SINGLE = 3;
    // 雙擊手勢
    private static final int TAP_DOUBLE = 4;
    
    // 手勢處理器
    private final GestureHandler mHandler;
    // 手勢監聽器
    private final MultiTouchGestureListener mListener;
    // 雙擊監聽器
    private MultiTouchDoubleTapListener mDoubleTapListener;
    
    // 長按允許閥值
    private boolean mIsLongpressEnabled;
    // 速度追蹤器
    private VelocityTracker mVelocityTracker;

    private class GestureHandler extends Handler {
        GestureHandler() {
            super();
        }
        GestureHandler(Handler handler) {
            super(handler.getLooper());
        }
        @Override
        public void handleMessage(Message msg) {
            int idx = (Integer) msg.obj;
            switch (msg.what) {
            case SHOW_PRESS: {
                if (idx >= sEventInfos.size()) {
//                    Log.w(MYTAG, CLASS_NAME + ":handleMessage, msg.what = SHOW_PRESS, idx=" + idx + ", while sEventInfos.size()="
//                            + sEventInfos.size());
                    break;
                }
                EventInfo info = sEventInfos.get(idx);
                if (info == null) {
//                    Log.e(MYTAG, CLASS_NAME + ":handleMessage, msg.what = SHOW_PRESS, idx=" + idx + ", Info = null");
                    break;
                }
                // 觸發手勢監聽器的onShowPress事件
                mListener.onShowPress(info.mCurrentDownEvent);
                break;
            }
            case LONG_PRESS: {
                // Log.d(MYTAG, CLASS_NAME + ":trigger LONG_PRESS");


                if (idx >= sEventInfos.size()) {
//                    Log.w(MYTAG, CLASS_NAME + ":handleMessage, msg.what = LONG_PRESS, idx=" + idx + ", while sEventInfos.size()="
//                            + sEventInfos.size());
                    break;
                }
                EventInfo info = sEventInfos.get(idx);
                if (info == null) {
//                    Log.e(MYTAG, CLASS_NAME + ":handleMessage, msg.what = LONG_PRESS, idx=" + idx + ", Info = null");
                    break;
                }
                dispatchLongPress(info, idx);
                break;
            }
            case TAP_SINGLE: {
                // Log.d(MYTAG, CLASS_NAME + ":trriger TAP_SINGLE");
                // If the user's finger is still down, do not count it as a tap
                if (idx >= sEventInfos.size()) {
//                    Log.e(MYTAG, CLASS_NAME + ":handleMessage, msg.what = TAP_SINGLE, idx=" + idx + ", while sEventInfos.size()="
//                            + sEventInfos.size());
                    break;
                }
                EventInfo info = sEventInfos.get(idx);
                if (info == null) {
//                    Log.e(MYTAG, CLASS_NAME + ":handleMessage, msg.what = TAP_SINGLE, idx=" + idx + ", Info = null");
                    break;
                }
                if (mDoubleTapListener != null && !info.mStillDown) { //手指在雙擊超時的閥值內未離開屏幕進行第二次單擊事件,則確定單擊事件成立(不再觸發雙擊事件)
                    mDoubleTapListener.onSingleTapConfirmed(info.mCurrentDownEvent);
                }
                break;
            }
            case TAP_DOUBLE: {
                if (idx >= sEventForDoubleTap.size()) {
//                    Log.w(MYTAG, CLASS_NAME + ":handleMessage, msg.what = TAP_DOUBLE, idx=" + idx + ", while sEventForDoubleTap.size()="
//                            + sEventForDoubleTap.size());
                    break;
                }
                EventInfo info = sEventForDoubleTap.get(idx);
                if (info == null) {
//                    Log.w(MYTAG, CLASS_NAME + ":handleMessage, msg.what = TAP_DOUBLE, idx=" + idx + ", Info = null");
                    break;
                }
                sEventForDoubleTap.set(idx, null);// 這個沒什麼好做的,就是把隊列中對應的元素清除而已
                break;
            }
            default:
                throw new RuntimeException("Unknown message " + msg); // never
            }
        }
    }
    /**
     * 觸發長按事件
     * @param info
     * @param idx
     */
    private void dispatchLongPress(EventInfo info, int idx) {
        mHandler.removeMessages(TAP_SINGLE, idx);//移除單擊事件確認
        info.mInLongPress = true;
        mListener.onLongPress(info.mCurrentDownEvent);
    }
    
     /**
     * 構造器1
     * @param context
     * @param listener
     */
    public MultiTouchGestureDetector(Context context, MultiTouchGestureListener listener) {
        this(context, listener, null);
    }
    /**
     * 構造器2
     * @param context
     * @param listener
     * @param handler
     */
    public MultiTouchGestureDetector(Context context, MultiTouchGestureListener listener, Handler handler) {
        if (handler != null) {
            mHandler = new GestureHandler(handler);
        } else {
            mHandler = new GestureHandler();
        }
        mListener = listener;
        if (listener instanceof MultiTouchDoubleTapListener) {
            setOnDoubleTapListener((MultiTouchDoubleTapListener) listener);
        }
        init(context);
    }
    /**
     * 初始化識別器
     * @param context
     */
    private void init(Context context) {
        if (mListener == null) {
            throw new NullPointerException("OnGestureListener must not be null");
        }
        mIsLongpressEnabled = true;
        int touchSlop, doubleTapSlop;
        if (context == null) {
            touchSlop = ViewConfiguration.getTouchSlop();
            doubleTapSlop = DOUBLE_TAP_SLAP;
            mMinimumFlingVelocity = ViewConfiguration.getMinimumFlingVelocity();
            mMaximumFlingVelocity = ViewConfiguration.getMaximumFlingVelocity();
        } else {//允許識別器在App中,使用偏好的設定
            final ViewConfiguration configuration = ViewConfiguration.get(context);
            touchSlop = configuration.getScaledTouchSlop();
            doubleTapSlop = configuration.getScaledDoubleTapSlop();
            mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity();
            mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity();
        }
        mTouchSlopSquare = touchSlop * touchSlop / 16;
        mDoubleTapSlopSquare = doubleTapSlop * doubleTapSlop;
    }
    /**
     * 設置雙擊監聽器
     * @param onDoubleTapListener
     */
    public void setOnDoubleTapListener(MultiTouchDoubleTapListener onDoubleTapListener) {
        mDoubleTapListener = onDoubleTapListener;
    }
    /**
     * 設置是否允許長按
     * @param isLongpressEnabled
     */
    public void setIsLongpressEnabled(boolean isLongpressEnabled) {
        mIsLongpressEnabled = isLongpressEnabled;
    }
    /**
     * 判斷是否允許長按
     * @return
     */
    public boolean isLongpressEnabled() {
        return mIsLongpressEnabled;
    }
    /**
     * 判斷當前事件是否為雙擊事件
     * <br/> 通過遍歷sEventForDoubleTap來匹配是否存在能夠構成雙擊事件的單擊事件
     * @param e
     * @return
     */
    private EventInfo checkForDoubleTap(MultiMotionEvent e) {
        if (sEventForDoubleTap.isEmpty()) {
//            Log.e(MYTAG, CLASS_NAME + ":checkForDoubleTap(), sEventForDoubleTap is empty !");
            return null;
        }
        for (int i = 0; i < sEventForDoubleTap.size(); i++) {
            EventInfo info = sEventForDoubleTap.get(i);
            if (info != null && isConsideredDoubleTap(info, e)) {
                sEventForDoubleTap.set(i, null);// 這個單擊事件已經被消耗了,所以置為null
                mHandler.removeMessages(TAP_DOUBLE, i);// 移除Handler內的為處理消息
                return info;
            }
        }
        return null;
    }
    /**
     * 判斷當前按下事件是否能和指定的單擊事件構成雙擊事件
     * 
     * @param info
     * @param secondDown
     * @return
     */
    private boolean isConsideredDoubleTap(EventInfo info, MultiMotionEvent secondDown) {
        if (!info.mAlwaysInBiggerTapRegion) { //如多第一次單擊事件有過較大距離的移動,則無法構成雙擊事件
            return false;
        }
        if (secondDown.getEventTime() - info.mPreviousUpEvent.getEventTime() > DOUBLE_TAP_TIMEOUT) {
            //如果第一次單擊的UP時間和第二次單擊的down時間時間間隔大於DOUBLE_TAP_TIMEOUT,也無法構成雙擊事件
            return false;
        }
        int deltaX = (int) info.mCurrentDownEvent.getX() - (int) secondDown.getX();
        int deltaY = (int) info.mCurrentDownEvent.getY() - (int) secondDown.getY();
        return (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare);//最後判斷兩次單擊事件的距離

    }


    /**
     * 將事件信息放入雙擊判斷隊列,並返回序號
     * 
     * @param info
     * @return
     */
    private int addIntoTheMinIndex(EventInfo info) {
        for (int i = 0; i < sEventForDoubleTap.size(); i++) {
            if (sEventForDoubleTap.get(i) == null) {
                sEventForDoubleTap.set(i, info);
                return i;
            }
        }
        sEventForDoubleTap.add(info);
        return sEventForDoubleTap.size() - 1;
    }

    /**
     * 從事件信息隊列中移除指定序號的事件
     * 
     * @param idx
     */
    private void removeEventFromList(int id) {
        if (id > sEventInfos.size() || id < 0) {
//            Log.e(MYTAG, CLASS_NAME + ".removeEventFromList(), id=" + id + ", while sEventInfos.size() =" + sEventInfos.size());
            return;
        }
        sEventInfos.set(id, null);
    }

    /**
     * 向事件隊列中添加新信息
     * 
     * @param e
     */
    private void addEventIntoList(EventInfo info) {
        int id = info.mCurrentDownEvent.getId();
        if (id < sEventInfos.size()) {
//            if (sEventInfos.get(id) != null)
//                Log.e(MYTAG, CLASS_NAME + ".addEventIntoList, info(" + id + ") has not set to null !");
            sEventInfos.set(info.mCurrentDownEvent.getId(), info);
        } else if (id == sEventInfos.size()) {
            sEventInfos.add(info);
        } else {
//            Log.e(MYTAG, CLASS_NAME + ".addEventIntoList, invalidata id !");
        }
    }
    
    public boolean onTouchEvent(MotionEvent ev) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);//把所有事件都添加到速度追蹤器,為計算速度做准備
        boolean handled = false;
        final int action = ev.getAction(); //獲取Action 
//        int idx = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;//獲取觸摸事件的序號
        int idx = ev.getPointerId(ev.getActionIndex());//獲取觸摸事件的id
        switch (action & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_POINTER_DOWN: {
            EventInfo info = new EventInfo(MotionEvent.obtain(ev));
            this.addEventIntoList(info);//將手勢信息保存到隊列中
            if (mDoubleTapListener != null) {//如果雙擊監聽器不為null
                if (mHandler.hasMessages(TAP_DOUBLE)) {
                    MultiMotionEvent e = new MultiMotionEvent(ev);
                    EventInfo origInfo = checkForDoubleTap(e);//檢查是否構成雙擊事件
                    if (origInfo != null) {
                        info.mIsDoubleTapping = true;
                        handled |= mDoubleTapListener.onDoubleTap(origInfo.mCurrentDownEvent);
                        handled |= mDoubleTapListener.onDoubleTapEvent(e);
                    }
                }
                if (!info.mIsDoubleTapping) {//當前事件不構成雙擊事件,那麼發送延遲消息以判斷onSingleTapConfirmed事件
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(TAP_SINGLE, idx), DOUBLE_TAP_TIMEOUT);
                    // Log.d(MYTAG, CLASS_NAME + ": add TAP_SINGLE");
                }
            }
            // 記錄X坐標和Y坐標
            info.mLastMotionX = info.mCurrentDownEvent.getX();
            info.mLastMotionY = info.mCurrentDownEvent.getY();
            
            if (mIsLongpressEnabled) {//允許長按
                mHandler.removeMessages(LONG_PRESS, idx);
                mHandler.sendMessageAtTime(mHandler.obtainMessage(LONG_PRESS, idx), info.mCurrentDownEvent.getEventTime() + TAP_TIMEOUT
                        + LONGPRESS_TIMEOUT);//延時消息以觸發長按手勢
                // Log.d(MYTAG, CLASS_NAME +
                // ":add LONG_PRESS to handler  for idx " + idx);
            }
            mHandler.sendMessageAtTime(mHandler.obtainMessage(SHOW_PRESS, idx), info.mCurrentDownEvent.getEventTime() + TAP_TIMEOUT);// 延時消息,觸發showPress手勢
            handled |= mListener.onDown(info.mCurrentDownEvent);//觸發onDown()
            break;
        }
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP: {
            MultiMotionEvent currentUpEvent = new MultiMotionEvent(ev);
            if (idx >= sEventInfos.size()) {
//                Log.e(MYTAG, CLASS_NAME + ":ACTION_POINTER_UP, idx=" + idx + ", while sEventInfos.size()=" + sEventInfos.size());
                break;
            }
            EventInfo info = sEventInfos.get(currentUpEvent.getId());
            if (info == null) {
//                Log.e(MYTAG, CLASS_NAME + ":ACTION_POINTER_UP, idx=" + idx + ", Info = null");
                break;
            }
            info.mStillDown = false;
            if (info.mIsDoubleTapping) { //處於雙擊狀態,則觸發onDoubleTapEvent事件
                handled |= mDoubleTapListener.onDoubleTapEvent(currentUpEvent);
            } else if (info.mInLongPress) {//處於長按狀態
                mHandler.removeMessages(TAP_SINGLE, idx);//可以無視這行代碼
                info.mInLongPress = false;
            } else if (info.mAlwaysInTapRegion) {//尚未移動過
                if (mHandler.hasMessages(TAP_SINGLE, idx)) {//還在雙擊的時間閥值內,所以要為雙擊判斷做額外處理
                    mHandler.removeMessages(TAP_SINGLE, idx);
                    info.mPreviousUpEvent = new MultiMotionEvent(MotionEvent.obtain(ev));
                    int index = this.addIntoTheMinIndex(info);// 把當前事件放入隊列,等待雙擊的判斷
                    mHandler.sendMessageAtTime(mHandler.obtainMessage(TAP_DOUBLE, index), info.mCurrentDownEvent.getEventTime()
                            + DOUBLE_TAP_TIMEOUT); // 將雙擊超時判斷添加到Handler
                    // Log.d(MYTAG, CLASS_NAME + ": add TAP_DOUBLE");
                }
                handled = mListener.onSingleTapUp(currentUpEvent);//觸發onSingleTapUp事件
            } else {
                // A fling must travel the minimum tap distance
                final VelocityTracker velocityTracker = mVelocityTracker;
                velocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);//計算1秒鐘內的滑動速度
                //獲取X和Y方向的速度
                final float velocityX = velocityTracker.getXVelocity(idx);
                final float velocityY = velocityTracker.getYVelocity(idx);
                // Log.i(MYTAG, CLASS_NAME + ":ACTION_POINTER_UP, idx=" + idx +
                // ", vx=" + velocityX + ", vy=" + velocityY);
                // 觸發滑動事件
                if ((Math.abs(velocityY) > mMinimumFlingVelocity) || (Math.abs(velocityX) > mMinimumFlingVelocity)) {
                    handled = mListener.onFling(info.mCurrentDownEvent, currentUpEvent, velocityX, velocityY);
                }
            }
            // Hold the event we obtained above - listeners may have changed the
            // original.
            if (action == MotionEvent.ACTION_UP) {    //釋放速度追蹤器
                mVelocityTracker.recycle();
                mVelocityTracker = null;
                // Log.w(MYTAG, CLASS_NAME +
                // ":ACTION_POINTER_UP, mVelocityTracker.recycle()");
            }
         
            info.mIsDoubleTapping = false;
            // Log.d(MYTAG, CLASS_NAME + "remove LONG_PRESS");
            // 移除showPress和長按消息
            mHandler.removeMessages(SHOW_PRESS, idx);
            mHandler.removeMessages(LONG_PRESS, idx);
            removeEventFromList(currentUpEvent.getId());//手指離開,則從隊列中刪除手勢信息
            break;
        }
        case MotionEvent.ACTION_MOVE:
            for (int rIdx = 0; rIdx < ev.getPointerCount(); rIdx++) {//因為無法確定當前發生移動的是哪個手指,所以遍歷處理所有手指
                MultiMotionEvent e = new MultiMotionEvent(ev, rIdx);
                if (e.getId() >= sEventInfos.size()) {
//                    Log.e(MYTAG, CLASS_NAME + ":ACTION_MOVE, idx=" + rIdx + ", while sEventInfos.size()=" + sEventInfos.size());
                    break;
                }
                EventInfo info = sEventInfos.get(e.getId());
                if (info == null) {
//                    Log.e(MYTAG, CLASS_NAME + ":ACTION_MOVE, idx=" + rIdx + ", Info = null");
                    break;
                }
                if (info.mInLongPress) {    //長按,則不處理move事件
                    break;
                }
                //當前坐標
                float x = e.getX();
                float y = e.getY();
                //距離上次事件移動的位置
                final float scrollX = x - info.mLastMotionX;
                final float scrollY = y - info.mLastMotionY;
                if (info.mIsDoubleTapping) {//雙擊事件
                    handled |= mDoubleTapListener.onDoubleTapEvent(e);
                } else if (info.mAlwaysInTapRegion) {//該手勢尚未移動過(移動的距離小於mTouchSlopSquare,視為未移動過)
                    // 計算從落下到當前事件,移動的距離
                    final int deltaX = (int) (x - info.mCurrentDownEvent.getX());
                    final int deltaY = (int) (y - info.mCurrentDownEvent.getY());
                    // Log.d(MYTAG, CLASS_NAME + "deltaX="+deltaX+";deltaY=" +
                    // deltaX +"mTouchSlopSquare=" + mTouchSlopSquare);
                    int distance = (deltaX * deltaX) + (deltaY * deltaY);
                    if (distance > mTouchSlopSquare) {     // 移動距離超過mTouchSlopSquare
                        handled = mListener.onScroll(info.mCurrentDownEvent, e, scrollX, scrollY);
                        info.mLastMotionX = e.getX();
                        info.mLastMotionY = e.getY();
                        info.mAlwaysInTapRegion = false;
                        // Log.d(MYTAG, CLASS_NAME +
                        // ":remove LONG_PRESS for idx" + rIdx +
                        // ",mTouchSlopSquare("+mTouchSlopSquare+"), distance("+distance+")");
                        // 清除onSingleTapConform,showPress,longPress三種消息
                        int id = e.getId();
                        mHandler.removeMessages(TAP_SINGLE, id);
                        mHandler.removeMessages(SHOW_PRESS, id);
                        mHandler.removeMessages(LONG_PRESS, id);
                    }
                    if (distance > mBiggerTouchSlopSquare) {//移動距離大於mBiggerTouchSlopSquare,則無法構成雙擊事件
                        info.mAlwaysInBiggerTapRegion = false;
                    }
                } else if ((Math.abs(scrollX) >= 1) || (Math.abs(scrollY) >= 1)) {//之前已經移動過了
                    handled = mListener.onScroll(info.mCurrentDownEvent, e, scrollX, scrollY);
                    info.mLastMotionX = x;
                    info.mLastMotionY = y;
                }
            }
            break;
        case MotionEvent.ACTION_CANCEL:
            cancel();//清理
        }
        return handled;
    }
    // 清理所有隊列
    private void cancel() {
        mHandler.removeMessages(SHOW_PRESS);
        mHandler.removeMessages(LONG_PRESS);
        mHandler.removeMessages(TAP_SINGLE);
        mVelocityTracker.recycle();
        mVelocityTracker = null;
        sEventInfos.clear();
        sEventForDoubleTap.clear();
    }

}

 


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved