彻底搞懂Android事件分发机制

45次阅读

共计 8586 个字符,预计需要花费 22 分钟才能阅读完成。

网上看到过很多人写的事件分发机制解析, 感觉表述都不是很清楚, 也可能没有看到写得好的文章, 所以自己重新看了一遍源码, 来彻底搞清楚 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 事件的.

正文完
 0