Android事件分发机制

<h1 align = "center">Android事件分发机制</h1>


前言:网上有很多关于Android事件分发的文章,但大多是基于使用经验或者Log来总结出来的,本文主要从源码进行分析,彻底了解Android事件分发的原理。以下的内容都是基于Android7.1源码的。

Activity的事件分发机制

一般情况下,对于应用层来说,事件的分发是从Activity接收到来自系统的TouchEvent开始的。Activity的dispatchTouchEvent首先被调用:

public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        // 可以重写这个方法,处理ACTION_DOWN事件,可以看出,任何事件序列都会首先调用这个函数,如果需要监听用户是否触摸屏幕,那么建议重写这个函数即可。
        onUserInteraction();
    }
    // 将事件交由Window处理,返回true表示事件已经消耗掉了,于是返回true告诉系统。
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    // 如果该事件没有被Window消耗掉,那么Activity的TouchEvent将会被调用。
    return onTouchEvent(ev);
}

Activity的事件分发比较简单,由源码可以看出,如果Window消耗了事件,或者Activity自身的onTouchEvent消耗了事件,都将会返回true,告诉系统事件已经被消耗掉。

我们知道,一个事件序列基本都是由ACTION_DOWN,ACTION_MOVE...,ACTION_MOVE,ACTION_UP构成的,在Activity的事件分发机制里面,一个事件序列里面的每个子事件的处理都是独立开来的,即,就算Activity不消耗ACTION_DOWN事件,接下来的ACTION_MOVE,ACTION_UP等事件都会继续传递给Activity处理。

Window的事件分发机制

在事件分发的过程中,Window只是作为中间的桥梁,这里没什么好说的。直接源码:

// 这个函数是在PhoneWindow里面的,实际上Activity中的Window,就是一个PhoneWindow
public boolean superDispatchTouchEvent(MotionEvent event) {
        // 直接交由DecorView处理
        return mDecor.superDispatchTouchEvent(event);
}

ViewGroup的事件分发机制

查看DecorView的源码发现,实际上,就是间接调用ViewGroup的dispatchTouchEvent,因为DecorView继承自FrameLayout,FrameLayout继承自ViewGroup,FrameLayout并没有重写dispatchTouchEvent函数,所以最终调用的是ViewGroup的dispatchTouchEvent。

public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

下面是把一些无关的代码删除后,ViewGroup的dispatchTouchEvent的实现,每一事件序列都维护着一个触摸链表,触摸链表的节点实体是TouchTarget,
事件序列中的任一事件,将会更新触摸链表。触摸链表是当前触点可以触摸到的子View的集合,例如一个ViewGroup中有2个子View,A和B,A和B有重合的部分,
如果手指触摸到重合的部分,那么触摸链表里面就是A和B,如果只是触摸到A独有的部分,那么触摸链表就是只有A。

public boolean dispatchTouchEvent(MotionEvent ev) {

    boolean handled = false;
    // 过滤一些不安全的触摸事件,比如当前View被别的可见分Window遮挡住了。
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // 清除之前的事件序列状态,另外,如果上一个事件序列结束后,当前这个ViewGroup被设置成不拦截事件的,
            // 那么在这个事件开始时,总是被设置成可以拦截事件。即设置FLAG_DISALLOW_INTERCEPT只是在一个事件序列内有效。
            // mFirstTouchTarget也会被清除。
            cancelAndClearTouchTargets(ev);
            resetTouchState();
        }

        // Check for interception.
        final boolean intercepted;
        // 一般情况下,如果是ACTION_DOWN事件,那么mFirstTouchTarget就为null,因为在上面的代码里面,ACTION_DOWN事件将会首先清除触摸链表
        // 如果不是ACTION_DOWN,而这个时候mFirstTouchTarget不为null,那么说明,ACTION_DOWN事件已经被当前ViewGroup的某一个子View消耗了
        // 于是会继续尝试拦截,于是可以得出:ViewGroup可以在事件序列的任一个节点阻止事件继续往下传递。
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            // 是否允许拦截事件,记住,FLAG_DISALLOW_INTERCEPT会在ACTION_DOWN事件到来时被重设,所以,
            // onInterceptTouchEvent 总是会被调用(ACTION_DOWN事件)
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                // 我们可以重写ViewGroup的onInterceptTouchEvent来决定要不要拦截事件
                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }
        } else {
            // 如果不是ACTION_DOWN,而这个时候mFirstTouchTarget又为null,那么说明ACTION_DOWN事件已经被当前的ViewGroup拦截了,或者是
            // 没有子View消耗ACTION_DOWN事件,
            // 于是,当前ViewGroup应该继续拦截接下来的一个事件序列内的所有事件。
            intercepted = true;
        }

        // 如果事件被拦截了,或者有子View处理了,都进行正常的分发。
        if (intercepted || mFirstTouchTarget != null) {
            ev.setTargetAccessibilityFocus(false);
        }

        // 检查该事件是否应该取消。
        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;
        // 事件不取消,而且不拦截
        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;
                    // 遍历所有子View,并将事件分发给子View(如果该子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范围内,那么View不能处理该事件。
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                        // 执行到这里的时候,说明View是具有响应当前事件的能力的(看上面的if语句)
                        // 假设当前事件不是DOWN事件,那么View应该就在触摸链表中了,即newTouchTarget不为null,
                        // 于是将会跳出循环
                        // 例外的情况是:如果是滑动的时候,滑到了一个全新的子View中,newTouchTarget == null,那么就会跑下面的代码
                        // 将该子View加入到触摸链表中。
                        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);
                        // 将事件传递给子View,子View的dispatchTouchEvent被调用
                        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不再触摸链表中,但是其能够响应当前的事件,所以理应将它加入到触摸链表中。
                            // 将该子View插入到触摸目标的链表头部。
                            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();
                }

                // 如果没有找到消耗当前事件的子View,那么最新的触摸目标指向最迟最近的的触摸目标
                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;
                }
            }
        }

        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) {
            // mFirstTouchTarget == null 说明触摸链表是空的,表示ViewGroup中没有子View响应该事件,那么
            // ViewGroup被当做是View对待,即ViewGroup的父类的dispatchTouchEvent被调用。ViewGroup的父类是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;
            // 遍历触摸链表,一个一个分发给链表中的view。
            while (target != null) {
                final TouchTarget next = target.next;
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    // 如果分发过了,那么就不再重复分发了
                    handled = true;
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
                    // 分发给链表中的view
                    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;
            }
        }

        // 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;
}

View的事件分发机制

View的事件分发比较简单,如果有设置onTouchListener,那么onTouchListener首先响应事件,
onTouchListener 如果不消耗事件,那么轮到onTouchEvent响应事件,如果连onTouchEvent都不消耗事件,
那么表明该View不消耗事件,返回false,将事件交由父View处理。

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

    // 如果当前View被别的可见的Window遮挡,那么无法响应事件
    // 例如Toast
    if (onFilterTouchEventForSecurity(event)) {
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        // 如果View有设置OnTouchListener,那么OnTouchListener首先响应事件。
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }

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

推荐阅读更多精彩内容