Touch 事件原理分析 (四)

2019-05-30  本文已影响0人  莫库施勒

中我们知道了Touch Event 是怎么从native层传导到framework 层并最终分发到ViewGroup和View,现在我们来分析TouchEvent在View中的传导。
我们知道在 ViewGroup 中首先是通过 dispatchTouchEvent 来开始的。

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    ... 
    boolean handled = false;
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();
        ...
        // 先检验事件是否需要被ViewGroup拦截
        final boolean intercepted;
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            // 校验是否给mGroupFlags设置了FLAG_DISALLOW_INTERCEPT标志位
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                // 走onInterceptTouchEvent判断是否拦截事件
                intercepted = onInterceptTouchEvent(ev);
            } else {
                intercepted = false;
            }
        } else {
            intercepted = true;
        }
        ...
        final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
        if (!canceled && !intercepted) {
            // 注意ACTION_DOWN等事件才会走遍历所有子View的流程
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                ...
                // 开始遍历所有子View开始逐个分发事件
                final int childrenCount = mChildrenCount;
                if (childrenCount != 0) {
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        // 判断触摸点是否在这个View的内部
                        final View child = children[i];
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            continue;
                        }
                        ...
                        // 事件被子View消费,退出循环,不再继续分发给其他子View
                        if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                            
                            ...
                            // addTouchTarget内部将mFirstTouchTarget设置为child,即不为null
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            alreadyDispatchedToNewTouchTarget = true;
                            break;
                        }
                    }
                }
            }
        }
        // 事件未被任何子View消费,自己处理
        if (mFirstTouchTarget == null) {
            // No touch targets so treat this as an ordinary view.
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);
        } else {
            // 将MotionEvent.ACTION_DOWN后续事件分发给mFirstTouchTarget指向的View
            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;
                    }
                    ...
                }
                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);
        }
    }
    return handled;
}
private void resetTouchState() {
    clearTouchTargets();
    resetCancelNextUpFlag(this);
    mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
private void clearTouchTargets() {
    TouchTarget target = mFirstTouchTarget;
    if (target != null) {
        do {
            TouchTarget next = target.next;
            target.recycle();
            target = next;
        } while (target != null);
        mFirstTouchTarget = null;
    }
}
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
    TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;
        ...
        
        // 注意传参child为null时,调用的是自己的dispatchTouchEvent
        if (child == null) {
            handled = super.dispatchTouchEvent(event);
        } else {
            handled = child.dispatchTouchEvent(transformedEvent);
        }
        return handled;
}
public boolean onInterceptTouchEvent(MotionEvent ev) {
    // 默认不拦截事件
    return false;
}
    // View.java
    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
            ListenerInfo li = mListenerInfo;
            // 判断事件是否先交给ouTouch方法处理
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
           // onTouch 事件未消费
            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.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

大体步骤如下:

  1. 判断事件是够需要被ViewGroup拦截
    判断的时候会判断 actionMasked、mFirstTouchTarget、mGroupFlags 这几个变量的状态,而 mGroupFlags 可以通过 requestDisallowInterceptTouchEvent 设置,所以有些滑动冲突的场景可以通过这个方法来阻止父 View 拦截事件。
    如果没有设置 FLAG_DISALLOW_INTERCEPT,就会执行 onInterceptTouchEvent 方法,如果返回 false ,即默认是不拦截事件的,需要向子类分发,接着执行 step2,否则执行 onTouchEvent,根据返回值判断是否自己消费
  2. 遍历所有子View,逐个分发事件
    进入遍历后,如果一个子View 触摸点不在 childView 范围内,则访问下一个;如果在范围内,则调用 dispatchTransformedTouchEvent 间接 dispatch 到子 View 中去。
    如果dispatchTransformedTouchEvent返回true,即事件被子View消费,就会把mFirstTouchTarget设置为child,即不为null,并将 alreadyDispatchedToNewTouchTarget 设置为true,然后跳出循环,事件不再继续传递给其他子View。
  3. 将事件交给ViewGroup自己或者目标子View处理
    经过上面一步后,如果mFirstTouchTarget仍然为空,说明没有任何一个子View消费事件,将同样会调用dispatchTransformedTouchEvent,但此时这个方法的 child 参数为null,所以调用的其实是super.dispatchTouchEvent(event),由于 ViewGroup 是 View 的子 View,所以事件将会使用View的dispatchTouchEvent(event) 方法判断是否消费事件。
    反之,如果mFirstTouchTarget不为null,说明上一次事件传递时,找到了需要处理事件的目标子View,此时,ACTION_DOWN的后续事件,如ACTION_UP等事件,都会传递至 mFirstTouchTarget 中保存的目标子View中。注意:如果在上一节遍历过程中已经把本次事件传递给子View,alreadyDispatchedToNewTouchTarget的值会被设置为true,代码会判断alreadyDispatchedToNewTouchTarget的值,避免做重复分发
  4. 若当前 ViewGroup 没有消费 Touch 事件,则会向父节点回溯,否则,消费 touch 事件

如果一个子View 没有消费ACTION_DOWN类型的事件,那么事件将会被另一个子View 或者ViewGroup自己消费,之后的事件都只会传递给目标子View(mFirstTouchTarget)或者ViewGroup自身。简单来说,就是如果一个View没有消费ACTION_DOWN事件,后续事件也不会传递进来。

上一篇下一篇

猜你喜欢

热点阅读