android TouchEvent分發筆記(2016.03.14更新)

奮鬥的Leo發表於2017-03-11

關於android的觸控事件這個知識點,一直感覺掌握不牢固,趁著前幾天有空,就仔細了看了一遍原始碼,順便寫了一下筆記,本來不想發成部落格,但考慮到有些可能分析的不對,所以發出來,希望大家多多指出問題,如果對你有少許的幫助,那就太好了。
本篇文章是基於android sdk 25的分析。
github

ACTION_DOWN或ACTION_POINTER_DOWN和ACTION_HOVER_MOVE 這三個事件稱為初始事件,因為只有在分發這三個事件時候,才會處理觸控目標。

ACTION_POINTER_DOWN和ACTION_HOVER_MOVE這兩個稱為多指初始事件

觸控目標指消費了初始事件的子檢視,資料結構為連結串列。新增加的子檢視為存放在頭部。

viewFlags & CLICKABLE == CLICKABLE || viewFlags & LONG_CLICKABLE == LONG_CLICKABLE || viewFlags & CONTEXT_CLICKABLE == CONTEXT_CLICKABLE 表示該檢視是 "可點選的"。

  1. Android的Touch事件由Activity->ViewGroup-View按順序分發(這裡只關心到Activity)
  2. 父檢視可以通過onInterceptTouchEvent來攔截事件分發到子檢視
  3. 子檢視可以呼叫requestDisallowInterceptTouchEvent來禁止父檢視攔截事件,但在ACTION_DOWN時,會清除該標記,即只在ACTION_DOWN時,呼叫該方法沒有效果。
  4. 如果子檢視沒有呼叫requestDisallowInterceptTouchEvent,那麼父檢視任何時候都可以攔截事件,即使子檢視已經消費了ACTION_DOWN,攔截事件後,會向子檢視分發一個ACTION_CANCEL事件會將該事件setAction(ACTION_CANCEL),分發給子檢視,之後的事件都將分發給父檢視。(2016.03.14更新)
  5. 父檢視分發事件時,只會在初始事件時候,來設定觸控目標。即如果子檢視沒消費這三個事件,也不會接收到後續的事件。
  6. 當分發多指初始事件時,沒有新的子檢視來消費該事件時,會將該事件的指標賦予觸控目標的尾部。
  7. 當沒有子檢視來消費事件時,會將事件分發給父檢視。(super.dispatchTouchEvent)
  8. View的事件分發,OnTouchListener.onTouch -> onTouchEvent -> TouchDelegate.onTouchEvent -> onClick/onLongClick等等
  9. 只要檢視是可點選的就預設會消費事件,即使該檢視是不啟用的(setEnabled(false)),只是不做點選處理反應。
  10. 一般情況下,只有在ACTION_DOWN中,返回值起主要作用,它決定了你是否消費接下來的所有事件,在消費了ACTION_DOWN後,在其他action中,返回false,依然可以接收到其他事件。(2016.03.14更新)

Activity中

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //使用者互動回撥
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
           //window是否消費該事件,touch事件分發從這裡開始
            return true;
        }
          //當前view沒有消費事件,則由activity處理
        return onTouchEvent(ev);
    }

//當前沒有任何view去消費事件時
public boolean onTouchEvent(MotionEvent event) {
          //window是否消費該事件,來關閉當前window
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }複製程式碼

PhoneWindow中

@Override
  public boolean superDispatchTouchEvent(MotionEvent event) {
        //window將事件委託給DecorView分發
        return mDecor.superDispatchTouchEvent(event);
    }複製程式碼

DecorView中

 public boolean superDispatchTouchEvent(MotionEvent event) {
           //呼叫父類的dispatchTouchEvent進行分發
        return super.dispatchTouchEvent(event);
    }複製程式碼

ViewGroup中

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
          //輸入事件一致性驗證者
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
      //輔助功能處理
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }
        //從這裡開始事件分發
        boolean handled = false;
        //安全策略過濾
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            //多指處理
              //多指情況下,POINTER:指標。(可以理解為單個手指)
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
              //處理一個初始按下事件ACTION_DOWN
            if (actionMasked == MotionEvent.ACTION_DOWN) {
              //丟棄之前的狀態
                // Throw away all previous state when starting a new touch gesture.
                // The framework may have dropped the up or cancel event for the previous gesture
                // due to an app switch, ANR, or some other state change.
              //取消,清除所有的觸控目標
                cancelAndClearTouchTargets(ev);
              //重置觸控狀態,這裡會將使用requestDisallowInterceptTouchEvent設定的狀態清除
              //這個狀態可以阻止父檢視(通過onInterceptTouchEvent)攔截子檢視Touch事件
                resetTouchState();
            }

            // Check for interception.
              //檢查是否攔截
            final boolean intercepted;
              //當為ACTION_DEON事件或觸控目標為不為null
              //即使已經有子檢視消費了事件,依然會執行判斷
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                  //檢查子檢視是否呼叫了requestDisallowInterceptTouchEvent來禁止父檢視攔截
                  //這個標記為ACTION_DOWN處理中被清除,即子檢視在ACTION_DOWN中呼叫是不起作用
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                      //檢查當前父檢視是否攔截該事件
                    intercepted = onInterceptTouchEvent(ev);
                      //恢復action,以防止在onInterceptTouchEvent被改變
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                  //當前不是ACTION_DOWN事件,且沒有觸控目標
                  //即子檢視如果不消費ACTION_DOWN,那麼後續事件也不會分發到。
                intercepted = true;
            }

            // If intercepted, start normal event dispatch. Also if there is already
            // a view that is handling the gesture, do normal event dispatch.
              //輔助功能
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            // Check for cancelation.
              //檢查是否為ACTION_CANCEL事件
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
              //檢查是否把事件分發給多個子檢視
              //通過setMotionEventSplittingEnabled設定,Android3.0以上預設開啟
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
              //當事件不取消而且不攔截
            if (!canceled && !intercepted) {

                // If the event is targeting accessiiblity focus we give it to the
                // view that has accessibility focus and if it does not handle it
                // we clear the flag and dispatch the event to all children as usual.
                // We are looking up the accessibility focused host to avoid keeping
                // state since these events are very rare.
                  //輔助功能
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;
                //1.當ACTION_DOWN事件(第一次按下)
                  //2.或事件可以分發給多個子檢視且ACTION+POINTER_DOWN(多指處理,當主指標還沒結束,又按下一個指標)
                  //3.或多指情況下,指標移動
                  //這裡的判斷表示,只有在ACTION_DOWN或者當前事件分發還沒結束,出現新的指標事件才會進行分發。但這裡的前提依然是,事件未取消和父檢視不攔截,和至少接收了ACTION_DOWN事件(即觸控目標連結串列不為空,ACTION_DOWN事件除外)
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                      //獲取事件的指標索引
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                      //指標id的位掩碼(用於獲取觸控目標捕獲的指標)
                      //TouchTarget.pointerIdBis 指標id的組合位掩碼,用於目標捕獲的所有指標
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;

                    // Clean up earlier touch targets for this pointer id in case they
                    // have become out of sync.
                      //清除這個指標作用的早先的觸控目標
                    removePointersFromTouchTargets(idBitsToAssign);

                    final int childrenCount = mChildrenCount;
                      //掃描可以接收事件的子檢視
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                          //獲取子檢視的事件分發列表
                          //這裡考慮了自定義的子檢視繪製順序
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                      //TODO:按buildTouchDispatchChildList()的返回 != null,即customOrder永遠為false,即自定義了繪製順序也不會改變事件分發順序
                      final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

                            // If there is a view that has accessibility focus we want it
                            // to get the event first and if not handled we will perform a
                            // normal dispatch. We may do a double iteration but this is
                            // safer given the timeframe.
                              //輔助功能
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }

                              //檢查子檢視是否可以接受事件和觸控事件是否作用在子檢視上
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                              //檢查當前子檢視是否已經存在觸控目標連結串列中
                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                // Child is already receiving touch within its bounds.
                                // Give it the new pointer in addition to the ones it is handling.
                                  //如果已經存在,則將新指標id賦值給它,並退出迴圈
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }
                            //檢查是否設定了取消標記
                              //TODO:但這裡沒對結果進行處理
                            resetCancelNextUpFlag(child);
                              //在這裡將事件交予子檢視進行分發
                              //一般能執行到這裡的:
                              //1.ACTION_DOWN
                              //2.多指情況下,指標作用於"新"檢視上
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                  //如果子檢視消費了事件
                                // Child wants to receive touch within its bounds.
                                  //儲存一些值
                                mLastTouchDownTime = ev.getDownTime();
                                if (preorderedList != null) {
                                    // childIndex points into presorted list, find original index
                                    for (int j = 0; j < childrenCount; j++) {
                                        if (children[childIndex] == mChildren[j]) {
                                            mLastTouchDownIndex = j;
                                            break;
                                        }
                                    }
                                } else {
                                    mLastTouchDownIndex = childIndex;
                                }
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                  //設定接收事件的子檢視為新的觸控目標,並設定為觸控目標連結串列的頭
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }

                            // The accessibility focus didn't handle the event, so clear
                            // the flag and do a normal dispatch to all children.
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        // Did not find a child to receive the event.
                        // Assign the pointer to the least recently added target.
                          //當觸控目標連結串列不為空,且當前事件沒有產生新的觸控目標(包含已有的觸控目標)來接收
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                          //找到觸控目標連結串列的尾部,將指標作用於它
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            // Dispatch to touch targets.
              //除了ACTION_DOWN,ACTION_POINTER_DOWN,ACTION_HOVER_MOVE
              //其他的事件的分發都從這裡
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                  //沒有子檢視接收事件,將事件分發給當前檢視
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it.  Cancel touch targets if necessary.
                  //將事件分發給觸控目標,除了新的觸控目標,因為在之前已經分發了
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                          //新的觸控目標,直接跳過
                        handled = true;
                    } else {
                          //檢查事件是否被取消或者被攔截
                          //即使子檢視在ACTION_DOWN中接收了事件,如果沒禁止攔截,父檢視依然可以攔截事件
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                          //分發到觸控目標
                          //當cancelChild=true,會分發ACTION_CANCEL事件
                          //dispatchTransformedTouchEvent中會判斷當前觸控目標是否包含指標id
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                          //當事件被取消,清除觸控目標連結串列
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }

            // Update list of touch targets for pointer up or cancel, if needed.
            if (canceled
                    || actionMasked == MotionEvent.ACTION_UP
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }複製程式碼
//取消和清除所有觸控目標
private void cancelAndClearTouchTargets(MotionEvent event) {
        if (mFirstTouchTarget != null) {
            boolean syntheticEvent = false;
            if (event == null) {
                final long now = SystemClock.uptimeMillis();
                //獲取一個ACTION_CANCEL事件
                event = MotionEvent.obtain(now, now,
                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
                syntheticEvent = true;
            }

            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
                resetCancelNextUpFlag(target.child);
               //分發ACTION_CANCEL事件
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            clearTouchTargets();

            if (syntheticEvent) {
                event.recycle();
            }
        }
    }
//清除所有觸控目標
 private void clearTouchTargets() {
        TouchTarget target = mFirstTouchTarget;
        if (target != null) {
            do {
                TouchTarget next = target.next;
                target.recycle();
                target = next;
            } while (target != null);
            mFirstTouchTarget = null;
        }
    }複製程式碼
//將事件分發到相應的目標
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
          //當事件取消時,會根據是否有觸控目標,向當前檢視或子檢視分發一個ACTION_CANCEL事件
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }

        // Calculate the number of pointers to deliver.
          //計算要傳遞的指標
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

        // If for some reason we ended up in an inconsistent state where it looks like we
        // might produce a motion event with no pointers in it, then drop the event.
          //該觸控目標不包含該指標,不分發
        if (newPointerIdBits == 0) {
            return false;
        }

        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
          //將事件進行分發,根據是否有觸控目標
        final MotionEvent transformedEvent;
        if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }

        // Perform any necessary transformations and dispatch.
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }複製程式碼

View中

public boolean dispatchTouchEvent(MotionEvent event) {
          //輔助功能
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

        boolean result = false;

          //除錯作用
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
              //停止巢狀滾動
            stopNestedScroll();
        }

        if (onFilterTouchEventForSecurity(event)) {
              //安全策略過濾
              //處理拖動滾動條
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
              //先呼叫OnTouchListener回撥
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

              //如果沒有OnTouchListener或者沒有消費,則呼叫onTouchEvent
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

          //除錯
        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
          //當ACTION_UP,ACTION_CANCEL或ACTION_DOWN且不消費,停止巢狀滾動
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }複製程式碼
public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
              //當該檢視不啟用時(setEnabled(false))
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
              //不啟用的檢視依然可以消費事件,只是沒有反應而已。
              //只要該檢視是 "可點選的"
            return (((viewFlags & CLICKABLE) == CLICKABLE
                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
        }
          //呼叫TouchDelegate
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
              //該檢視是 "可點選的"
            switch (action) {
                case MotionEvent.ACTION_UP:
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                          //當我們設定 "按下" 狀態或 "延時按下" 狀態
                        // take focus if we don't have it already and we should in
                        // touch mode.
                          //獲取焦點
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                              //如果設定了 "延時按下" 狀態,那在實際釋放之前設定為 "按下" 狀態
                            setPressed(true, x, y);
                       }

                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                              //如果沒有呼叫長按動作而且不忽略下一個抬起的事件,清除長按回撥,不回撥長按事件
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                  //獲取不了焦點,表示正在按下狀態,才處理點選事件
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                          //清除 "按下" 狀態
                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }

                       //取消點選檢測計時器。即 "延時按下" 狀態
                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    mHasPerformedLongPress = false;

                    //執行按鈕的相關操作
                    //比如選單欄點選
                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    //檢查當前是否位於滾動容器中
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    //當父檢視處於滾動中,則延時處理 "按下" 狀態
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(0, x, y);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    //當事件取消時候,清理
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_MOVE:
                    drawableHotspotChanged(x, y);

                    // Be lenient about moving outside of buttons
                    //當手指移動時候,不再處於當前檢視範圍,取消事件
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        removeTapCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            // Remove any future long press/tap checks
                            removeLongPressCallback();

                            setPressed(false);
                        }
                    }
                    break;
            }

              //不管有沒有處理,只要該檢視具有 "可點選" ,就會預設消費掉該事件
             //即使該檢視不啟用,依然會消費事件,只是不執行 "點選" 事件。
            return true;
        }

        return false;
    }複製程式碼

相關文章