ViewGroup的事件分发

上一篇讲了view的事件分发,比较简单。接下来看看稍微复杂一点的ViewGroup。
我们还是先用log看一下主要方法是如何执行的:

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;
        //1.没有被遮挡
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // 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.
                //2.清空异常及已有状态 给所有之前选择出的Target发送Cancel事件,
                //确保之前Target能收到完整的事件周期; 
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            //3.如果是ACTION_DOWN事件,或者已经将之前的ACTION_DOWN事件分发给childview
            //注:当ViewGroup的childview成功处理时,会将mFirstTouchTarget 指向该childview
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //4.是否禁止拦截
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                //5.如果没有禁止拦截
                if (!disallowIntercept) {
                    //6.判断是否拦截,也就是onInterceptTouchEvent的返回值
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                }
                  //7.如果禁止拦截,当然就不拦截了
                   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.
                // 8.在这种情况下,actionMasked != ACTION_DOWN && mFirstTouchTarget == null
                // 第一次的down事件没有被此ViewGroup的children处理掉(要么是它们自己不处理,要么是ViewGroup从一
                // 开始的down事件就开始拦截),则接下来的所有事件
                // 也没它们的份,即不处理down事件的话,那表示你对后面接下来的事件也不感兴趣
                //意味着上一次ACTION_DOWN 事件没有分发下去,所以后续事件不再询问,直接拦截
                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.
            //9.此touch事件是否cancel
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            //10.是否拆分事件,与多点触控有关,默认拆分
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            //11.找到的childview,接下来ViewGroup判断要将此touch事件交给他处理
            TouchTarget newTouchTarget = null;
            //12.down或pointer_down事件已经被处理
            boolean alreadyDispatchedToNewTouchTarget = false;
            //13.没有cancel也没有拦截,即有效事件
            if (!canceled && !intercepted) {

                // If the event is targeting accessiiblity 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;

                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;
                        //14.遍历childview
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            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.
                            //15.不可见而且没有正在执行的动画,跳过
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }
                            //16.手指不在该childview范围中,跳过
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
                            //17.寻找childview对应的TouchTarget
                            newTouchTarget = getTouchTarget(child);
                            //18.已经有对应的TouchTarget,比如在同一个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.
                                //19. newTouchTarget已经有了,跳出for循环
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }
                           
                            //20.复位标志位,避免上次操作带来的影响
                            resetCancelNextUpFlag(child);
                            //21.重点:dispatchTransformedTouchEvent方法当child为空时调用自身dispatchTouchEvent
                            //否则调用child的dispatchTouchEvent方法,在这child不为空,所以将事件分发下去
                            // 需要注意的是,有可能用户一个手指按在了child1上,另一个手指按在了child2上
                            // 这样TouchTarget的链就形成了(TouchTarget内部类似单链表)
                            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();
                                //22. 如果处理掉了的话,将此child添加到touch链的头部
                                // 注意这个方法内部会更新 mFirstTouchTarget
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                // 23.down或pointer_down事件已经被处理了
                                alreadyDispatchedToNewTouchTarget = true;
                                //24.退出循环
                                break;
                            }

                            // 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();
                    }
                    
                    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;
                    }
                }
            }
            // 25.非down事件直接从这里开始处理,不会走上面的一大堆寻找TouchTarget的逻辑

            // Dispatch to touch targets.
            //26.如果没有找到合适的childview,交给自己处理,调用super.dispatchTouchEvent(event);
            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;
                //27.上面说了,用户有可能不同的手指按在不同的childview上,所以要遍历TouchTarget的链表
                while (target != null) {
                    final TouchTarget next = target.next;
                    //28.已经处理过,不再处理
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        //检查是否需要拦截
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        // 如果ViewGroup从半路拦截(cancelChild为true)了touch事件则给touch链上的child发送cancel事件
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            // TouchTarget链中任意一个处理了则设置handled为true
                            handled = true;
                        }
                        // 如果cancel的话,则回收此target节点
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }

            // Update list of touch targets for pointer up or cancel, if needed.
            // 取消或up事件时resetTouchState
            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;
    }

主要的功能,上面注释了一部分。这里总结一下:

ACTION_DOWN

首先,ACTION_DOWN 事件的任务就是找到分发对象(找到接收事件分发的childview)

1.在viewgroup没有被遮罩的情况下,先清空异常及已有状态,给所有之前选择出的Target发送Cancel事件,确保之前Target能收到完整的事件周期; 清除已有Target,复位所有标志位(如PFLAG_CANCEL_NEXT_UP_EVENT、FLAG_DISALLOW_INTERCEPT等) 。
对应编号1-2
2.判断是否需要拦截,某个 view 一旦开始处理事件,如果不消费 ACTION_DOWN 事件,则同一事件序列中的其他事件不会再交给它来处理,直接拦截。如果是ACTION_DOWN 事件,或者向下分发了ACTION_DOWN 事件,则调用onInterceptTouchEvent以确定当前ViewGroup是否拦截该Down事件。与此同时,还要关注禁止拦截属性。禁止拦截由public void requestDisallowInterceptTouchEvent(boolean disallowIntercept)方法设置,当disallowIntercept为true时,禁止拦截。
对应编号3-8
3.如果事件没有被拦截也没有被cancel,遍历childview寻找合适的分发对象。{如果该childview不可见而且没有正在执行的动画,跳过。如果手指不在该childview范围中,也跳过。找到合适的childview之后,判断是否已经有一个手指按在此childview上(对应编号18),如果是直接跳出循环,因为已经找到了合适的分发对象(即此newTouchTarget.child)。如果否,先复位该childview的状态,然后调用childview的dispatchTouchEvent方法把事件分发下去,并把该childview添加到TouchTarget 链表中,对mFirstTouchTarget赋值(编号3处用到,如果mFirstTouchTarget!=null,说明已经将事件分发下去了)。然后退出循环}(花括号内为循环体)。如果没有合适的childview,则交给自己处理,调用super.dispatchTouchEvent(event);(编号26)
对应编号13-26 。 至此,找到了合适的childview,

非ACTION_DOWN 事件

上面我们得到了TouchTarget,其中的链表记录了接收事件的childview(可能是多个,多点触控)。所以我们先遍历target,检查是否被ViewGroup从半路拦截,如果是,分发cancel,否者正常的把事件分发下去。

图片说明

最后一图以蔽之。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容