徹底搞懂Android事件分發機制

網上看到過很多人寫的事件分發機制解析,感覺表述都不是很清楚,也可能沒有看到寫得好的文章,所以自己重新看了一遍源碼,來徹底搞清楚Android事件分發機制.

觸摸事件有哪些以及怎麼從Activity傳遞到DecorView大家可以上網查下,幾個重要方法的基本調用順序,這些很容易搜到,我們重點關注事件從ViewGroup到View的事件具體的執行過程.

1 Android事件分發涉及到的方法主要有

dispatchTouchEvent()事件分發
onInterceptTouchEvent()攔截事件
onTouchEvent()處理事件
requestDisallowInterceptTouchEvent()請求不要攔截事件

2 測試類介紹

BigGroup類型ViewGroup
SmallGroup類型ViewGroup
TestView類型View*(clickable默認false)
圖片描述

3 默認情況下的事件分發流程(View.onTouchEvent()返回super.onTouchEvent())

log如下所示:
BigGroup: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
BigGroup: onInterceptTouchEvent() called with: ev = [ACTION_DOWN]
SmallGroup: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
SmallGroup: onInterceptTouchEvent() called with: ev = [ACTION_DOWN]
TestView: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
TestView: onTouchEvent() called with: event = [ACTION_DOWN]
SmallGroup: onTouchEvent() called with: event = [ACTION_DOWN]
BigGroup: onTouchEvent() called with: event = [ACTION_DOWN]

我們看到不管怎麼點擊滑動,都只會觸發DOWN事件的流程,我們來看下這是爲什麼,首先我們來看下ViewGroup的dispatchTouchEvent()

    ///////////ViewGroup
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
       ...省略部分代碼
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
            //如果是DOWN事件,清除標記,恢復一些標記狀態
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            //判斷是否攔截
            final boolean intercepted;
            //觸發DOWN事件或者mFirstTouchTarget不是Null,纔會走if裏面的邏輯
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    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.
                //不是DOWN事件 mFirstTouchTarget爲空  攔截後續事件
                intercepted = true;
            }

             ...省略部分代碼

            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            //事件沒有被取消或者沒有被攔截執行if中邏輯
            if (!canceled && !intercepted) {
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                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
                    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();
                        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 (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }
                            //判斷child是否可以響應事件 是否點擊在了View的範圍之內
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
                            //獲取上次響應事件的View,DOWN事件時候newTouchTarget爲Null
                            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.
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
                            //很重要的一個方法,在下面我們會看這個方法做了什麼
                            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();
                                //在這個方法中把child賦值給了mFirstTouchTarget
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }                           
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                   ...
                }
            }

            // Dispatch to touch targets.
            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 {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        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;
                }
            }

            ...
        }    

        ...
        return handled;
    }
    
    
    
    //最重要的幾行代碼的邏輯
    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;
        ...省略部分代碼
        // Perform any necessary transformations and dispatch.
        //child爲空調用父View的dispatchTouchEvent
        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());
            }
            //child不爲空調用child的dispatchTouchEvent方法
            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }
    //默認返回false
     public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }
    //////////View
     public boolean dispatchTouchEvent(MotionEvent event) {
        ...

        boolean result = false;
        ...

    
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            //我們看到有mOnTouchListener,並且onTouch返回true,就沒有onTouchEvent啥事了
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

       ...
        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();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

       ...
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                  ...
                    break;

                case MotionEvent.ACTION_DOWN:
                   ...
                    break;

                case MotionEvent.ACTION_CANCEL:
                   ...
                    break;
            }

            return true;
        }

        return false;
    }

我們梳理下DOWN事件的執行流程:
1 觸發BigGroup的dispatchTouchEvent()方法
2 給intercepted賦值,disallowIntercept默認爲false,這是就會觸發onInterceptTouchEvent()方法,onInterceptTouchEvent默認返回false.intercepted賦值爲false
3 接下來走到if (!canceled && !intercepted)的邏輯裏面去了,注意注意intercepted爲true的話這個方法直接就跳過去了.在這段邏輯裏遍歷所有的子View,接下來進入淘汰機制,child不能獲得焦點,下一個,然後看看View不可見,下一個,沒有點到child範圍之內,下一個.剩下來的娃會執行dispatchTransformedTouchEvent方法
4 接下來dispatchTransformedTouchEvent中調用了child的dispatchTouchEvent方法
5 執行dispatchTouchEvent的child就是我們的SmallGroup,執行邏輯同2-4
6 這次執行dispatchTouchEvent的child就是我們的TestView了
7 TestView dispatchTouchEvent中首先判斷了有沒有onTouchListener,判斷onTouch方法的返回值.我們肯定沒寫的了,接下來會執行onTouchEvent
8 在TestView onTouchEvent中我們看到如果這個View可點擊就返回true,不可點擊就返回false.TestView不可點擊,所以返回了false
9 觸發了連鎖反應,TestView dispatchTouchEvent返回false
10SmallGroup dispatchTransformedTouchEvent返回了false, mFirstTouchTarget爲null
11SmallGroup再次執行dispatchTransformedTouchEvent child參數爲null,執行super.dispatchTouchEvent(),ViewGroup的super最後就是View,所以會執行邏輯7-9,不同的事主角事SmallGroup
12BigGroup dispatchTransformedTouchEvent返回了false, mFirstTouchTarget爲null,重複步驟11,主角BigGroup,DOWN事件結束

mFirstTouchTarget爲null會有什麼影響呢?後續事件中intercepted爲true,執行dispatchTransformedTouchEvent child參數爲null,執行super.dispatchTouchEvent(),事件直接傳遞不下來了,後續事件都接收不到了
所以log只能看到有關於DOWN事件的.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章