Android事件分发机制源码执行流程分析

事件机制在应用开发中非常重要,手指与界面任何交互都会转化成一个个事件,通过事件机制完成一系列的逻辑处理,最终找到事件的响应者。理解事件机制我们才能准确的把握在具体情况下如何把事件交由相应的View进行处理,开发过程中经常会遇到事件处理的问题,如自定义view、滑动冲突处理等

思考几个问题:
1.onTouchListener、onClickListener 哪个优先级高?
2. 自定义View时处理事件逻辑时有一个非常长的神仙方法requestDisallowInterceptTouchEvent(),可以拒绝父布局拦截事件,知道是怎么实现的吗?
3. 假如父View拦截了down事件,那么子View还能接收到move、up等事件吗?

进入正题前首先明确几个概念:
分发事件:外层视图将事件传递给内层视图,对应方法dispatchTouchEvent()
消费事件:视图树中某个View处理了事件,其onTouchEvent ()返回true
拦截事件:视图树中的某个View拦截了事件不再向内层视图传递,其onInterceptTouchEvent () 返回true

一张粗略的流程图

Android事件分发机制源码执行流程分析_第1张图片
一个触摸事件经过系统事件输入最终反映到与用户交互得界面即当前Activity上,框架层通过经典的责任链设计模式,由Activity逐层向内分发事件dispatchTouchEvent,并在分发事件的过程中,逐层询问是否拦截或消费事件。
如果事件在视图树的某一层被拦截则不再继续向内分发事件,转而询问拦截事件的View是否消费事件,如果事件被消费则此次事件传递结束,如果事件未被消费则将此事件将沿着分发事件的反方向逐层调用onTouchEvent返回false,最终由根View的dispatchTouchEvent决定Activity的onTouchEvent方法是否被调用;
如果事件未被任何View拦截则分发到最内层子View,调用其onTouchEvent方法询问是否消费事件,若不消费则事件则同上所述,最终逐层调用onTouchEvent交由Activity处理。

事件分发机制的详细执行过程:

Android事件分发机制源码执行流程分析_第2张图片
接下来跟着源码带着疑问,看一看事件的分发流程

Activity向ViewGroup分发事件的过程

既然事件是从Activity开始分发那我们先看一下Activity的dispatchTouchEvent方法:

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //通过window把事件向内部分发
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

通过其return语句可以看到,只有getWindow().superDispatchTouchEvent(ev)返回false也即整个Activity视图树的所有视图都不消费事件时,其onTouchEvent才有机会被执行到,这样可以得出事件机制最基础的结论,事件从Activity开始分发逻辑,最终的响应逻辑又回到Activity中,形成了一个完整的事件循环。当然,前提时子View不对事件做任何处理。

接下来看一下window的分发方法superDispatchTouchEvent,它在Window是一个抽象方法,所以看一下它在Window的唯一子类PhoneWindow中的具体实现:

  @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

它内部直接调用了一个叫mDecor属性的同名方法,我们知道这个mDecor其实是每一个Activity创建时框架给页面添加的根View详见此篇,它内部又直接调用了其父类ViewGroup的dispatchTouchEvent()。事件分发逻辑在这里正式进入了View树的范围。

ViewGroup分发事件的过程

接下来进入到ViewGroup的分发事件方法:

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    
         (省略部分代码......)

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // down事件时表明是一个新的事件序列,清空保存的事件处理状态
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            //检查事件拦截情况
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                 // 如果是down事件或在down时已经找到了消费事件的子View
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                // 不是down事件,且没有其他子View消费事件即表示down事件是被此View消费的,那么后续同一系列事件,直接交由此View拦截处理
                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;
            // 事件没有被拦截时,处理其子View事件分发相关逻辑
            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;
                            
                    removePointersFromTouchTargets(idBitsToAssign);

                    final int childrenCount = mChildrenCount;
                    //遍历子View找到能消费事件的子View
                    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;
                        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;
                            }
							
							// 判断是子View状态可用且事件坐标在该View区域,如果不是跳出本次循环
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                // 如果此View已经被添加到待分发事件的Target链表则直接break循环
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
                            // 查找消费事件的子View(如果是ViewGroup递归ViewGroup视图树的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();
                                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;
                    }
                }
            }

            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // 在子View中未找到此事件的消费者则分发给View自己
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // 遍历tartget链表,将
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    //过滤已经被分发过的事件 如 54~56行ACTION_DOWN/ACTION_POINTER_DOWN/ACTION_HOVER_MOVE
                    //这三个事件已经在之前的逻辑中分发过了
                    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;
                }
            }

      	 (省略部分代码......)
      	
        return handled;
    }

从源码里可以看到,ViewGroup的事件分发主要有一下几个步骤:

  1. 判断事件拦截情况;19~33行
    先判断不是down事件且没有其他子View消费事件即表示down事件是被此View消费的,那么后续同一系列事件,直接交由此View处理intercepted变量置为true。这样我们开篇第三个问题就有了答案
    接下来判断ViewGroup是否有dissAllowIntercepter标识,如果有则直接将intercepted变量置为flase;如果没有此标识则通过onIntercepterTouchEvent返回值来判断是否拦截事件。这里也回答了我们的第二个问题,原来拒绝父View拦截事件源码实现如此简单
  2. 分发事件给子View;50~140行
    如果事件不被拦截(此处还有是否是cancel事件综合判断)则遍历子View,判断子view是否可用以及是否在点击区域,调用dispatchTransformedTouchEvent查找消费事件的子View。
  3. 分发事件给自己;145~149行
    如果事件被拦截、没有子View或者遍历子View未找到消费事件的子View,则该事件交给自己处理

那么事件是如何交由子View的呢?接着看一下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();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                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.
        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());
            }
			//事件分发给子View处理
            handled = child.dispatchTouchEvent(transformedEvent);
        }

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

这个方法里主要对多点触摸的逻辑做了一些处理,同时对事件进行了一些加工添加了一些offset偏移量属性。这里我们不关心多点触摸的问题,主要看一下事件分发的流程,55~66行可以看出:
当此方法的child参数传入为null时直接调用了super.dispatchTouchEvent(),事件逻辑转移到其父类View的dispatchTouchEvent ()中;
当child不为null时又需要考虑两种情况,child是View或child是ViewGroup,当child是ViewGroup时child.dispatchTouchEvent ()明显是又递归查找子ViewGroup中是否有消费事件的子View。在ViewGroup的dispatchTouchEvent() 的104行child传入参数子View,147行child传入参数为null。

View分发事件的过程

不管怎么分发逻辑最终都会转移到View的dispatchTouchEvent ()中,我们来看一下此方法:

public boolean dispatchTouchEvent(MotionEvent event) {
        
        (省略部分代码...)
        
        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();
        }

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

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

主要看一下17~32行:
首先判断了当View是enable状态且是作用在scrollBar上或有设置onTouchListener时且onTouch方法返回true时,则事件被消费,不再调用onTouchEvent();否则事件将会交给View的onTouchEvent()处理。所以onTouch()的优先级要比onTouchEvent()要高。看一下onTouchEvent方法:

 public boolean onTouchEvent(MotionEvent event) {
 
   		(省略部分代码......)
   		    	
            switch (action) {
                case MotionEvent.ACTION_UP:
   						  (省略部分代码......)
                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }
	
                       	(省略部分代码......)
                       	
                    break;
                    
      			 (省略部分代码......)
      			    	
            }
    		(省略部分代码......)
        return false;
    }

我们知道一个完整的点击事件需要一个down事件和一个up事件共同组成,看源码onClickListener是在onTouchEvent()处理up事件中通过performClick() 间接调用的,因此onTouchLisenter的优先级高于onClickListener。

事件传递到onTouchEvent ()由其返回值决定是否消费事件,View将该结果返回给父View的,如果返回true则事件被消费,如果返回false则父View将事件分发给自己的onTouchEvent (),这样就将执行结果一层层的返回给了外层View,由Window的dispatchTouchEvent ()返回值决定Activity是否调用onTouchEvent() ,最终形成事件传递流程一个完整的回路。

你可能感兴趣的:(源码分析)