阅读 561

探究事件分发

为什么掌握事件分发

面对滑动冲突时如何解决,如何自定义可双指扩大缩小的view,都需要掌握事件分发的相关知识

首先在探究前,要明白什么是事件序列

什么是事件序列

一个完整的事件序列包括ACTION_DOWNACITON_MOVEACTION_UPACTION_CANCEL,因为包括多指操作,所有会包含ACTION_POINTER_DOWNACTION_POINTER_UP

还有一点,如何标记被触摸的view,而且还是多指操作,通过TouchTarget

TouchTarget

TouchTarget的作用是用来标记被触摸的view以及触摸id集合,是一个单向链表结构,ViewGroup中的mFirstTouchTarget作为链表的头结点

其中比较重要的几个成员变量

  • public View child 表示被触摸的子view
  • public int pointerIdBits 这个int值是用来标记被触摸的id集合,因为是多指触摸,而一个bit可以表示一个id,int是32bit,所以可以表示32个id

对象缓存池

因为整个触摸过程中会不断的创建对象,所以内部实现了对象的缓存池,通过obtain获取对象,recycle缓存对象,

如何事件分发

dispatchTransformedTouchEvent方法作用:将一个motion event(事件序列)转换为特定子view的坐标,过滤掉无关的pointer ids,如果有必要重写其action。如果cilid为空,则假定将此MotionEvent发送给此ViewGroup。 整个事件分发的核心在于ViewGroup的dispatchTouchEvent

dispatchTouchEvent

该方法其实总共做了三件事情

  • 1.检查是否要拦截事件分发
  • 2.如果不拦截,就遍历子view,询问是否拦截
  • 3.根据变量mFirstTouchTarget重新分发事件

下面,逐步剖析下每步具体做了什么操作

1)检查是否要拦截事件分发

            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //A
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); 
                } else {
                    intercepted = false;
                }
            } else {
                intercepted = true;
            }
复制代码

注释A:该标记对应的requestDisallowInterceptTouchEvent方法,如果为true代表子view请求父view不拦截该事件,如果不是子view请求的不拦截的话,再有onInterceptTouchEvent判断是否拦截

从这段逻辑也可以看出,如果down事件中拦截了事件,那么整个事件序列都会交给其处理,除非子view请求不要拦截

2)如果不拦截,就遍历子view,寻找可以消费触摸事件的子view

整个第二步的核心,就是找到TouchTarget

 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                ...
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
复制代码

那如果找不到呢?就会将触摸id添加到最近最少使用的target,才用头插法添加到TouchTarget链表

第二步中还有个关键点,就是会按照层级的高低顺序遍历子view,这也体现了常规的“所见即所得”的思想,即用户看到的最上面view的就是级别最高的

比如

<LinearLayout>
    <FrameLayout>
        <TextView/>
    </FrameLayout>
</LinearLayout>
复制代码

对应的层级顺序可以用下图表示

3)根据变量mFirstTouchTarget重新分发事件

如果mFirstTouchTarget存在,则遍历TouchTarget,设置事件

如果mFirstTouchTarget不存在的话,就会将child置为null,传入dispatchTransformedTouchEvent,实际是将cancel封装成MotionEvent,传入自己的OnTouchEvent

其中还有需要注意的点,就是

 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        //注意这个布尔值
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                       ...
                    }
复制代码

本来已经分发给子view的事件,父view会取消掉,那什么情况会触发这个判断呢?

有个经典的例子就是ScollView内包裹Button,按住Button的时候持有这个事件,但是如果滚动屏幕,这时候ScollView就会抢占事件

事件分发的本质

整个事件分发的过程中,会从上到下查看是否需要拦截事件,不管拦截不拦截,都会逐级上报,把拦截结果告诉上层,实际体现的是递归的思路

参考

附完整释义

ViewGruop#dispatchTouchEvent

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
        //分发前的准备工作
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

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

            // 检查是否拦截事件
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // 保存action
                } else {
                    intercepted = false;
                }
            } else {
                //触摸view不存在或者不是最初的down事件,所以view group会继续拦截事件
                intercepted = true;
            }

            //如果已经拦截或者有view捕获了手势,就开始正常的事件分发。
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            //检查是否是cancel事件
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // 更新包含多指操作down事件的touch target
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            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;
                    //清除早期该触摸id的touch target,防止数据不同步
                    removePointersFromTouchTargets(idBitsToAssign);

                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        //从层级高的到层级低的,逐级遍历,查找可以接受事件的子view
                        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;
                            }

                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                //子view在范围之内接收到了触摸事件,更新触摸id,除了之前已经持有的触摸id还需要增加触摸id
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                //子view想要接收触摸事件
                                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;
                            }
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        //没有找到可以接收触摸事件的子view,则将触摸id添加到最近最少使用的target
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            // 根据mFirstTouchTarget的值分发事件
            if (mFirstTouchTarget == null) {
                //如果没有touch targets,则将此ViewGroup作为普通view
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                //分发给touch targets,但是要排除掉已经分发过的target touch。必要情况下,取消touch targets的分发
                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;
                }
            }

            // 更新up或者cancel事件
            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;
    }
复制代码

ViewGroup#requestDisallowInterceptTouchEvent

requestDisallowInterceptTouchEvent方法作用:ture表示子view不想让其父view在执行onInterceptTouchEvent拦截事件。本父view会逐级往上传递。这个parent在响应触摸期间,必须执行chlid的请求(也就是说,只会在parent接收到up或者cancel时,清除标记,对应的标记为FLAG_DISALLOW_INTERCEPT

ViewGroup#onInterceptTouchEvent

    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;
    }
复制代码

作用:用来拦截所有的屏幕触摸事件,可以在分发给chlid时查看事件,并且在任何时刻掌握当前手势的所有权。

ViewGroup#dispatchTransformedTouchEvent

将触摸事件转换为特定子view的坐标空间

关注下面的标签,发现更多相似文章
评论