Android事件分发机制

定义

将点击事件传递到某个view&处理的整个过程。

事件分发顺序

Activity -> ViewGroup -> View

事件分发的方法

  • dispatchTouchEvent(),分发(传递)事件。
  • onInterceptTouchEvent(),判断是否拦截事件(只存在viewGroup,普通的view没有此事件)。
  • onTouchEvent(),处理点击事件。

onInterceptTouchEvent()和onTouchEvent()都在dispatchTouchEvent()中调用

简述

当点击的时候,首先调用viewgroup的dispatchTouchEvent,如果顶级的viewgroup拦截了此事件(onInterceptTouchEvent返回true),则此事件交给顶级的viewgroup进行处理。如果不拦截则交给子view进行处理,如果子view不进行处理则再返回父级进行处理,依次向上推。

View的事件调度顺序

onTouchListener > onTouchEvent > onLongClickListener > onClickListener

ACTION_DOWN事件会从Activity-ViewGroup-View-ViewGroup的顺序一直查看是否消费了onTouchEvent事件,如下

I/System.out: Activity   dispatchTouchEvent ----> 0
I/System.out: ViewGroup  dispatchTouchEvent ----> 0
I/System.out: ViewGroup  onInterceptTouchEvent ----> 0
I/System.out: View       dispatchTouchEvent ----> 0
I/System.out: View       onTouchEvent ----> 0
I/System.out: ViewGroup  onTouchEvent ----> 0

ACTION_UP,ACTION_MOVE,ACTION_CANCEL则会在消费了事件的View直接传给onTouchEvent结束事件,如下

I/System.out: Activity   dispatchTouchEvent ----> 1
I/System.out: ViewGroup  dispatchTouchEvent ----> 1
I/System.out: ViewGroup  onTouchEvent ----> 1
ViewGroup的dispatchTouchEvent源码分析
@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)) {
            //如果事件发生的View在的窗口,没有被遮挡

            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            //判断是不是Down事件,如果是的话,就要做初始化操作
            // Handle an initial 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);
                resetTouchState();
            }

            //是否拦截事件
            // Check for interception.
            final boolean intercepted;
            //如果当前是Down事件,或者已经有处理Touch事件的目标了
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //判断允不允许这个View拦截
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //允许拦截事件
                    intercepted = onInterceptTouchEvent(ev);//判断是不是拦截了
                    //重新恢复Action,以免action在上面的步骤被人为地改变了
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                //如果说,事件已经初始化过了,并且没有子View被分配处理,那么就说明,这个ViewGroup已经拦截了这个事件
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                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.
            //检查事件是否被取消了
            //如果viewFlag被设置了PFLAG_CANCEL_NEXT_UP_EVENT ,那么就表示,下一步应该是Cancel事件
            //或者如果当前的Action为取消,那么当前事件应该就是取消了。
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            //如果需要(不是取消,也没有被拦截)的话,那么在触摸down事件的时候更新触摸目标列表
            //split代表,当前的ViewGroup是不是支持分割MotionEvent到不同的View当中
            // 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 (!canceled && !intercepted) {

                // 如果事件是针对可访问性焦点视图,我们将其提供给具有可访问性焦点的视图。
                // 如果它不处理它,我们清除该标志并像往常一样将事件分派给所有的 ChildView。
                // 我们检测并避免保持这种状态,因为这些事非常罕见
                // If the event is targeting accessibility 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;

                //如果是个全新的Down事件
                //或者是有新的触摸点
                //或者是光标来回移动事件(不太明白什么时候发生)
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {

                    //这个事件的索引,也就是第几个事件,如果是down事件就是0
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    //获取分配的ID的bit数量
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;

                    // 清除此指针ID的早期触摸目标,防止不同步。
                    // Clean up earlier touch targets for this pointer id in case they
                    // have become out of sync.
                    removePointersFromTouchTargets(idBitsToAssign);

                    final int childrenCount = mChildrenCount;
                    //如果新的触摸对象为null并且当前ViewGroup有子元素
                    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 preorderedList = buildTouchDispatchChildList();
                        //是否使用自定义的顺序来添加控件
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        //从最后向前扫描  主要能找到最新加入的view
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            //如果是用了自定义的顺序来添加控件,那么绘制的View的顺序和mChildren的顺序是不一样的
                            //所以要根据getChildDrawingOrder取出真正的绘制的View
                            //自定义的绘制,可能第一个会画到第三个,和第四个,第二个画到第一个,这样里面的内容和Children是不一样的
                            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;
                            }

                            // 检查View是否允许接受事件(即处于显示状态(VISIBLE)或者正在播放动画)
                            // 或者 检查触摸位置是否在View区域内
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
                            //获取新的触摸对象,如果当前的子View在之前的触摸目标的列表当中就返回touchTarget
                            newTouchTarget = getTouchTarget(child);
                            //子View不在之前的触摸目标列表那么就返回null
                            if (newTouchTarget != null) {
                                //如果新的触摸目标对象不为空,那么就把这个触摸的ID赋予它,这样子,
                                //这个触摸的目标对象的id就含有了好几个pointer的ID了
                                // Child is already receiving touch within its bounds.
                                // Give it the new pointer in addition to the ones it is handling.
                                newTouchTarget.pointerIdBits |= idBitsToAssign;// ChildView 已经准备好接受在其区域内的事件。
                                break;
                            }
                            //如果子View不在之前的触摸目标列表中,先重置childView的标志,去除掉CACEL的标志
                            resetCancelNextUpFlag(child);

                            //调用子View的dispatchTouchEvent,并且把pointer的id 赋予进去
                            //如果说,子View接收并且处理了这个事件,那么就更新上一次触摸事件的信息,
                            //并且为创建一个新的触摸目标对象,并且绑定这个子View和Pointer的ID
                            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;
                            }

                            //可访问性焦点没有处理事件
                            //对所有child进行分发
                            // 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();
                    }

                    // 没有找到 ChildView 接收事件
                    // 将指针交给最近添加的目标
                    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;
                    }
                }
            }

            // 子视图未消耗Touch Event 或者 被拦截未向子视图派发Touch Event
            // 分发 TouchTarget
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                // 没有 TouchTarget,在当前 ViewGroup 处理。
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // 分发TouchTarget,如果我们已经分发过,则避免分配给新的目标。
                // 如有必要,取消分发。
                // 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;
                //遍历TouchTargt树.分发事件,如果我们已经分发给了新的TouchTarget那么我们就不再分发给newTouchTarget
                while (target != null) {
                    final TouchTarget next = target.next;
                    //已将将事件分配给了新的触摸
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        //是否让child取消处理事件,如果为true,就会分发给child一个ACTION_CANCEL事件
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //分发事件
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        //cancelChild也就是说,派发给了当前child一个ACTION_CANCEL事件,
                        //那么就移除这个child
                        if (cancelChild) {
                            //没有父节点,也就是当前是第一个TouchTarget
                            //那么就把头去掉
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                //把下一个赋予父节点的上一个,这样当前节点就被丢弃了
                                predecessor.next = next;
                            }
                            //回收内存
                            target.recycle();
                            //把下一个赋予现在
                            target = next;
                            //下面的两行不执行了,因为我们已经做了链表的操作了。
                            //主要是我们不能执行predecessor=target,因为删除本节点的话,父节点还是父节点
                            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) {
                //如果是多点触摸下的手指抬起事件,就要根据idBit从TouchTarget中移除掉对应的Pointer(触摸点)
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }
整体逻辑
  • DOWN事件进来,清空状态
  • 为intercepted赋值,判断是否拦截
  • 不拦截则从ChildView中找到可以接收事件的ChildView
  • 判断ChildView是否处理了事件,mFirstTouchTarget为空,表示不管是down还是其他事件没有ChildView要处理在当前 ViewGroup 处理;否则,该事件序列已经有孩子处理了

你可能感兴趣的:(Android事件分发机制)