android TouchEvent分發筆記(2016.03.14更新)

關於android的觸摸事件這個知識點,一直感受掌握不牢固,趁着前幾天有空,就仔細了看了一遍源碼,順便寫了一下筆記,原本不想發成博客,但考慮到有些可能分析的不對,因此發出來,但願你們多多指出問題,若是對你有少量的幫助,那就太好了。
本篇文章是基於android sdk 25的分析。
githubjava

ACTION_DOWN或ACTION_POINTER_DOWN和ACTION_HOVER_MOVE 這三個事件稱爲初始事件,由於只有在分發這三個事件時候,纔會處理觸摸目標。android

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

觸摸目標指消費了初始事件的子視圖,數據結構爲鏈表。新增長的子視圖爲存放在頭部。github

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中app

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

DecorView中ide

public boolean superDispatchTouchEvent(MotionEvent event) {
           //調用父類的dispatchTouchEvent進行分發
        return super.dispatchTouchEvent(event);
    }複製代碼

ViewGroup中post

@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中ui

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;
    }複製代碼
相關文章
相關標籤/搜索