美文网首页
Android触摸事件分发机制

Android触摸事件分发机制

作者: 我爱吃土豆丶 | 来源:发表于2018-09-07 09:29 被阅读0次

    前言

    事件传递主要涉及如下重要方法:

    • dispatchTouchEvent 负责事件分发
      Activity-->PhoneWindow-->DecorView-->ViewGroup-->View
      若事件不被拦截,最终会被传递到子View,由子View来进行消费。若子View不消费,则层层回朔之上。
    • onInterceptTouchEvent 负责事件拦截
      ViewGroup中的方法,是否对事件进行拦截,若拦截,则自己来消费,若不拦截,将事件分发至子View
    • onTouchEvent 事件消费

    下面从代码角度具体来进行分析

    ViewGroup中的dispatchTouchEvent

    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);
            }
            //标记事件是否处理完,若传递给子view,并且子view消费(返回true),则为true
            boolean handled = false;
            //过滤掉一些不合法的事件:当前的View的窗口被遮挡了
            if (onFilterTouchEventForSecurity(ev)) {
                //重置前面为0 ,只留下后八位,用于判断相等时候,可以提高性能。
                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);
                    //清空掉mFirstTouchTarget
                    resetTouchState();
                }
                //检测是否拦截
                // Check for interception.
                final boolean intercepted;
                //如果当前的事件是DOWN事件,或者是已经有了触摸事件的目标
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || mFirstTouchTarget != null) {
                    //判断是否允许进行拦截,该变量主要由requestDisallowInterceptTouchEvent方法来确定,该方法由子View发起
                    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                    //允许拦截
                    if (!disallowIntercept) {
                        //根据onInterceptTouchEvent方法,判断当前是否拦截
                        intercepted = onInterceptTouchEvent(ev);
                        //重置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;
                //标记触摸事件有没有传递给新的触摸对象,并且消费了,即调用子View的dispatchTouchEvent并返回true
                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;
                  
                    //如果是个全新的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;
                        //清理之前触摸这个指针标识,以防他们的目标变得不同步。
                        // 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);
                            //遍历子View,找到一个可以接收事件的子View (就是定位到你当前手指触摸的坐标,找到当前该坐标内的子View) 
                            // 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;
                            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;
                                }
    
                                //如果child不可以接收这个触摸的事件,或者触摸事件发生的位置不在这个View的范围内
                                if (!canViewReceivePointerEvents(child)
                                        || !isTransformedTouchPointInView(x, y, child, null)) {
                                    ev.setTargetAccessibilityFocus(false);
                                    continue;
                                }
    
                                //获取新的触摸对象,如果当前的子View在之前的触摸目标的列表当中就返回touchTarget
                                //子View不在之前的触摸目标列表那么就返回null
                                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.
                                    //如果新的触摸目标对象不为空,那么就把这个触摸的ID赋予它,这样子,
                                    //这个触摸的目标对象的id就含有了好几个pointer的ID了
                                    //已经获得触摸对象,直接跳出循环
                                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                                    break;
                                }
                                //表示之前没有触摸对象缓存,newTouchTarget=null
                                //如果子View不在之前的触摸目标列表中,先重置childView的标志,去除掉CACEL的标志
                                resetCancelNextUpFlag(child);
                                //调用子View的dispatchTouchEvent,并且把pointer的id 赋予进去
                                //如果说,子View接收并且处理了这个事件,那么就更新上一次触摸事件的信息,
                                //并且为创建一个新的触摸目标对象,并且绑定这个子View和Pointer的ID
                                if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                    //子View在范围内接收并消费了这个事件
                                    // 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);
                                   //此时事件已经成功分发至子View,更改状态,防止后续再次分发
                                    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();
                        }
    
                        //如果newTouchTarget为null,就代表,这个事件没有找到子View去处理它,
                        //那么,如果之前已经有了触摸对象(比如,我点了一张图,另一个手指在外面图的外面点下去)
                        //那么就把这个之前那个触摸目标定为第一个触摸对象,并且把这个触摸(pointer)分配给最近添加的触摸目标
                        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) {
                    // No touch targets so treat this as an ordinary view.
                    //那么就表示我们要自己在这个ViewGroup处理这个触摸事件了
                    handled = dispatchTransformedTouchEvent(ev, canceled, null,
                            TouchTarget.ALL_POINTER_IDS);
                } else {
                    //遍历TouchTargt树.分发事件,如果我们已经分发给了新的TouchTarget那么我们就不再分发给newTouchTarget
                    // 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;
                        //根据上面的标记,防止再次分发
                        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;
                                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;
        }
    

    方法中涉及到涉及到的重要的传递事件方法:

    //该方法涉及到是否像子View传递还是调用super传递给自身来处理
    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());
                }
    
                handled = child.dispatchTouchEvent(transformedEvent);
            }
    
            // Done.
            transformedEvent.recycle();
            return handled;
        }
    

    ViewGroup中的onInterceptTouchEvent

    public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                    && ev.getAction() == MotionEvent.ACTION_DOWN
                    && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                    && isOnScrollbarThumb(ev.getX(), ev.getY())) {
                return true;
            }
            return false;
        }
    自定义View时,重写此方法,根据自己的条件来决定是否拦截
    

    View中的dispatchTouchEvent

    上面说到,在ViewGroup的dispatchTouchEvent中,若是事件没被拦截,最终会调用View的dispatchTouchEvent,而且若返回true,则表明子View接收了事件并消费了,那么现在来看看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();
            }
    
            if (onFilterTouchEventForSecurity(event)) {
                if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                    result = true;
                }
                //noinspection SimplifiableIfStatement
                ListenerInfo li = mListenerInfo;
                //可以看出,如果设置了ouTouch监听,并且返回true,则代表消费了,此时将不会传递到下面的onTouchEvent
                if (li != null && li.mOnTouchListener != null
                        && (mViewFlags & ENABLED_MASK) == ENABLED
                        && li.mOnTouchListener.onTouch(this, event)) {
                    result = true;
                }
            
                //如果上述不成立,就交由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;
        }
    

    由上面我们可以看出,如果用户设置了onTouch的监听,并且返回true,那么事件就有onTouch消费,即不会有后续。如果没有,那么将交由onTouchEvent方法来消费。
    来看下onTouchEvent:

    //前后省略了很多,其实主要就是根据事件的类型,来进行各个事件的消费,然后返回true。这边主要来看下onTouchEvent里面的performClick方法
    ...
    public boolean onTouchEvent(MotionEvent event) {
        switch (action) {
                    case MotionEvent.ACTION_UP:
                          if (mPerformClick == null) {
                                        mPerformClick = new PerformClick();
                                    }
                                    if (!post(mPerformClick)) {
                                        performClick();
                                    }
                    break;
         }
    }
    ...
    

    具体来看下performClick方法:

    public boolean performClick() {
            final boolean result;
            final ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnClickListener != null) {
                playSoundEffect(SoundEffectConstants.CLICK);
                li.mOnClickListener.onClick(this);
                result = true;
            } else {
                result = false;
            }
    
            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
    
            notifyEnterOrExitForAutoFillIfNeeded(true);
    
            return result;
        }
    

    很熟悉,这就是我们的点击事件,看来它的回调是发生在onTouchEvent里面的UP事件里。
    所以简单的得出了onTouch—>onTouchEvent—>onClick三个执行顺序。

    总结

    最后用一段伪代码来总结下:

    TouchTarget mFirstTouchTarget=null;//子控件是否消费
    
    public boolean dispatchTouchEvent(MotionEvent event) {
             boolean isIntercept =false;//是否拦截
             if(onInterceptTouchEvent(event)){//是否拦截
                isIntercept=true;
            }
            if(!isIntercept){//如果没有拦截
    
                //执行子控件的dispatchTouchEvent
                boolean consume= child.dispatchTouchEvent(event);
                if(!consume){//子控件没有消费事件
                    mFirstTouchTarget = null;
                }else{
                    //子控件消费了事件,给mFirstTouchTarget赋值
                    mFirstTouchTarget = addTouchTarget(child, idBitsToAssign);
                }
            }else{//如果拦截,子控件没有消费事件
    
                mFirstTouchTarget = null;
            }
            if(mFirstTouchTarget==null){
                //子控件没有消费事件
                return onTouchEvent(event);
            }else{//子控件消费了事件
                return true;
            }
    
        }
    

    相关文章

      网友评论

          本文标题:Android触摸事件分发机制

          本文链接:https://www.haomeiwen.com/subject/nbitgftx.html