ViewGroup的事件分发

上篇本来想把Activity的事件分发和本篇放在一起写,但ViewGroup的事件分发内容实在太多,所以分开了。本篇正式开始学习ViewGroup事件分发源码,ViewGroup事件分发的源码较长,所以下面分析的时候分段贴出源码。

ViewGroup的dispatchTouchEvent()源码:

 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);
    }
  
    //dispatchTouchEvent的返回值handle默认值为false
    boolean handled = false;
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        // Handle an initial down.
        //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.
            //重要代码@1:清除TouchTarget目标控件
            cancelAndClearTouchTargets(ev);
            //重置touch状态(后面的禁止拦截状态就被重置了)
            resetTouchState();
        }

注释中标注的重要代码@1比较重要,ViewGroup在处理down事件的时候会首先清空touchTarget,也就是清空消费上一次touch事件的子View(事件传递链上所有target view)。 继续看下面的代码:

  //重要代码@2:整段都重要
  // Check for interception.
        //是否拦截标志位,默认为false
        final boolean intercepted;
        //如果是down事件,或者FirstTouchTarget不为null,也就是有子控件消费touch事件
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            //禁止拦截标志位,默认为false,在子控件可通过getParent().requestDisallowInterceptTouchEvent()修改其值
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            //不禁止拦截,也就是要拦截事件
            if (!disallowIntercept) {
                //修改拦截标志位
                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                //不拦截事件,拦截标志位为false
                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事件,并且也没有子控件消费touch事件,就拦截
            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.
        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;

这一整段代码主要是检测是否拦截事件,通过重要代码@1,再结合上面的源码可以得出结论:
1,如果在子View中调用getParen().requestDisallowInterceptTouchEvent(true)不让父控件拦截事件,那么该方法必须写在子View的dispatchTouchEvent(),或者onTouch()亦或者onTouchEvent()中(如果子View的onTouch()返回true,则只能写在dispatchTouchEvent()或者onTouch()中,具体原因看View的事件分发),因为如果写在这两个方法外面,touch事件的down事件传递到ViewGroup中的时候,会在重要代码1处重置禁止拦截标志位为false,相当于没改变禁止拦截标志位,父控件还是会拦截事件。

2,如果父View下面有子View消费touch事件,并且子View没有调用requestDisallowInterceptTouchEvent(true),无论是down,move,up事件,父View的onInterceptTouchEvent()都会执行,父View都会拦截

3,如果是down事件,即使父View下面没有子View消费touch事件,onInterceptTouchEvent()也会执行,也就是说,父View无论如何都会拦截down事件,子View调用requestDisallowInterceptTouchEvent(true)也不能控制

4,onInterceptTouchEvent()只有在2种情况下不会执行:

  • 不是down事件,并且ViewGroup下面的子View没有消费touch事件
  • 不是down事件,并且ViewGroup有子View消费touch事件,但是子View调用了requestDisallowInterceptTouchEvent(true)

源码继续:

  //不是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;
            //如果是down事件,或者多个手指按下,或者鼠标在ViewGroup上移动,就开始分发事件
            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.
                  //按Z轴的排列,从上到下倒序添加ViewGroup的直接子View到集合
                    final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;
                  //对ViewGroup的直接子View进行倒序遍历
                    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.
                        if (childWithAccessibilityFocus != null) {
                            if (childWithAccessibilityFocus != child) {
                                continue;
                            }
                            childWithAccessibilityFocus = null;
                            i = childrenCount - 1;
                        }
                      //判断是否在子View的范围内,或者子View是否在播放动画,都不符合,则继续遍历
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                        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);
                        //重要代码@3:将事件分发给子View,如果有子View消费了Touch事件就进入if内部
                        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();
                            //有子View消费Touch事件,将它插入到事件传递链上,并给mFirstTouchTarget赋值
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            alreadyDispatchedToNewTouchTarget = true;
                            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;
                }
            }
        }

ViewGroup的事件分发最关键的就是这段,这段主要是分发事件。从一进来的第一个if语句和第二个if语句,可以知道:只有在down事件,并且没有拦截的情况下,ViewGroup才会把down事件给分发给子View. 并且在分发的时候如果找到了有子View能够处理当前的down事件,newTouchTarget=mFirstTouchTarget,他们都不为null,并且alreadyDispatchedToNewTouchTarget的值也被置为true
看下dispatchTransformedTouchEvent()的源码:

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
        View child, int desiredPointerIdBits) {
    final boolean handled;

    // Canceling motions is a special case.  We don't need to perform any transformations
    // or filtering.  The important part is the action, not the contents.
    final int oldAction = event.getAction();
    //cancel值为true,或者是cancel事件
    if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
        event.setAction(MotionEvent.ACTION_CANCEL);
        if (child == null) {
          //child为null,调用ViewGroup自己的父类,也就是View的dispatchTouchEvent()
            handled = super.dispatchTouchEvent(event);
        } else {
            //child不为null,调用child的
            handled = child.dispatchTouchEvent(event);
        }
        event.setAction(oldAction);
        return handled;
    }

    // Calculate the number of pointers to deliver.
    final int oldPointerIdBits = event.getPointerIdBits();
    final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

    // If for some reason we ended up in an inconsistent state where it looks like we
    // might produce a motion event with no pointers in it, then drop the event.
    if (newPointerIdBits == 0) {
        return false;
    }

    // If the number of pointers is the same and we don't need to perform any fancy
    // irreversible transformations, then we can reuse the motion event for this
    // dispatch as long as we are careful to revert any changes we make.
    // Otherwise we need to make a copy.
    final MotionEvent transformedEvent;
    if (newPointerIdBits == oldPointerIdBits) {
        if (child == null || child.hasIdentityMatrix()) {
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                final float offsetX = mScrollX - child.mLeft;
                final float offsetY = mScrollY - child.mTop;
                event.offsetLocation(offsetX, offsetY);

                handled = child.dispatchTouchEvent(event);

                event.offsetLocation(-offsetX, -offsetY);
            }
            return handled;
        }
        transformedEvent = MotionEvent.obtain(event);
    } else {
        transformedEvent = event.split(newPointerIdBits);
    }

    // Perform any necessary transformations and dispatch.
    //跟上面的cancel事件一样
    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());
        }

        handled = child.dispatchTouchEvent(transformedEvent);
    }

    // Done.
    transformedEvent.recycle();
    return handled;
}

在分发事件的步骤中重要代码@3处 :
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {....}
传递cancel为false,并且child不为null,所以dispatchTransformedTouchEvent()会调用最后的
handled = child.dispatchTouchEvent(transformedEvent(),也就是子View的dispatchTouchEvent(),如果子View也是ViewGroup,那么就又重新走一遍从本篇开始到此处的代码,如果子View不是ViewGroup,那么就走一遍View的事件分发

通过事件的递归传递,就可以找到消费down事件的目标mFirstTouchTarget,如果找到了,mFirstTouchTarget不为null, 如果没找到,mFirstTouchTarget为null.

继续源码:

// Dispatch to touch targets.
        //没有子View消费down事件
        if (mFirstTouchTarget == null) {
            // No touch targets so treat this as an ordinary view.
          //交由ViewGroup自己处理
            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;
         //alreadyDispatchedToNewTouchTarget 每次进入dispatchTouchEvent()都会被置为false,newTouchTarget也会被置为null,
        //只有在分发down事件时找到能够处理touch事件的目标子控件了,这两个条件才会被满足
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    handled = true;      //分发down事件,找到目标子控件了,返回true
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;   //有子View消费了down事件,但是在move事件ViewGroup拦截了,cancelChild为true

                //重要代码@4:cancelChild如果为true,分发一个cancel事件给child,并且ViewGroup自己返回true
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {    //找到了目标子控件,分发move和up事件给子view
                        handled = true;    //如果子View的move和up事件也返回了true,viewGroup的dispatchTouchEvent()也返回true
                    }
                  //cancleChild为true,把mFirstTouchTarget 回收重置为null
                    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.
        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;
}

在上面的重要代码@4中,可以看到:
1,如果子View消费了down事件(mFirstTouchTarget不为null),但是ViewGroup拦截了move事件(intercepted为true),cancelChild 为true,dispatchTransformedTouchEvent()第二个参数就为true,move事件不会传递到子View,而是会传递一个cancel事件给子View来结束本次move事件的传递。并且cancelChild为true,会把mFirstTouchTarget置为null,直到下一次down事件到来之前,后面的任何事件(move,up)都会交个这个ViewGroup处理(调用自身的onTouchEvent()),不会再传递给子View。(子View的cancel事件返回值也会影响到Activity的onTouchEvent()是否触发)

2,如果子View消费了down事件,在move事件的时候,ViewGroup也没有拦截,但是子View自己不想处理move事件(dispatchTransformedTouchEvent()返回false),handle这时候就为默认值false,ViewGroup的dispatchTouchEvent()会直接在最后返回false,不会去调用自身的onTouchEvent()去处理当前的move事件,而是把move事件层层往上传递到Activity,直接交给Activity处理。当前ViewGroup,以及中间的所有ViewGroup都不会处理当前以及后续的move事件。但是后续的up事件会正常下发到子view,不会交给Activity处理。

前面在具体的重要代码处已经总结了关键流程,懒得再总结了。

在这里还想谈下学习事件分发的感悟:
以前总是记别人的总结:“如果子view不处理touch事件,事件会回传给父View处理”,那是down,move,up事件的返回值统一都一样的情况下,才是对的,但是想上面的情况,我们可能会对不同的事件分别做不同的处理,这个结论就不对了。所以只记结论,只看什么“图解事件分发”的流程图,不看源码和测试,只会颠覆你的三观:为什么会这样,明明这个流程图就是这样的,怎么事件不传给父View了!!! 哈哈,Reading the fucking source code! 答案在源码!

ps:源码比较复杂,有很多细节没有分析到(能力也有限),阅读源码主要把握流程,不能只见树木不见森林

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

推荐阅读更多精彩内容