美文网首页
View事件分发浅析

View事件分发浅析

作者: BooQin | 来源:发表于2018-07-21 20:41 被阅读633次

View事件分发

在Android中,View无处不在,不管是一个普通的视图,还是一个复杂的布局,都是依靠View来实现。而View中的事件分发和处理,是其核心知识点之一,也是开发者学习View时的难点。

在分析事件处理前,我们需要明白,android中一个完整的手势(gesture)包括如下4个操作:

  • DOWN: 当用户手指按下时
  • MOVE: 当用户开始滑动时
  • UP: 用户抬起手指
  • CANCEL: 取消操作,事件被无法到达时

任何一个手势都需要从DOWN开始。

在事件分发中,我们需要区分View和ViewGroup,虽然后者也是继承与View,但是ViewGroup重写了dispatchTouchEvent()方法,同时,也只有在ViewGroup会处理onInterceptTouchEvent()方法,而一个事件分发过程,是从一个ViewGroup开始,在这过程中我们需要了解以下三个重要的方法:

  • dispatchTouchEvent()
  • onInterceptTouchEvent()
  • onTouchEvent()

其中,dispatchTouchEvent负责将事件分发到其子View或当前View中。onInterceptTouchEvent方法仅存在与ViewGroup中,用于拦截点击事件,优先级高于onTouchEvent。onTouchEvent中完成对点击事件的处理,可以拦截并消耗事件。三者的关系可以根据如下伪代码来表示:

public boolean dispatchTouchEvent(Motion e){
     boolean result=false;
     if(onInterceptTouchEvent(e)){
     //如果当前View截获事件,那么事件就会由当前View处理,即调用onTouchEvent()
        result=onTouchEvent(e);
     }else{
        //如果不截获那么交给其子View来分发
        result=child.dispatchTouchEvent(e);
     }
     return result;
}

dispatchTouchEvent

dispatchTouchEvent是事件分发的主入口,即所有的事件处理都是从这里开始的,在View和ViewGroup中有着不同实现。

View中的实现

首先是在View中,dispatchTouchEvent将事件分配到对应方法中处理手势事件,可以看以下源码:

    /**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    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)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            //将事件从分配到OnTouchListener接口来处理事件
            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;
    }

这里顺带说下,我们在View中常用的两个方法OnTouchListener和OnClick。在dispatchTouchEvent中,会首先判断OnTouchListener是否为空,如果代码中对View调用了setOnTouchListener,那么这里会直接处理,同时跳过对onTouchEvent(OnClick在该方法中被执行)的调用,否则会直接执行onTouchEvent事件。因此,在View中,OnTouchListener的优先级高于OnClick,同时一个手势操作最多只能被其中一个处理。大致的关系可以通过下图来理解:

View中dispatchTouchEvent关系图

ViewGroup中的实现

与View不同,在ViewGroup中的dispatchTouchEvent,负责将事件传递到子事件中,而不会直接对该事件进行处理。部分源码如下:

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
            ……
            //非取消状态和中断状态
            if (!canceled && !intercepted) {
                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 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 = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        //循环子View,传递手势事件。
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder
                                    ? getChildDrawingOrder(childrenCount, i) : i;
                            final View child = (preorderedList == null)
                                    ? children[childIndex] : preorderedList.get(childIndex);
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                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);
                            //分发到子View中
                            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;
                            }
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }
                    ……
                }
            }

           ……
    }

该方法中会调用dispatchTransformedTouchEvent方法:

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

        ……

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

可以看出最终还是会执行到View中的dispatchTouchEvent。

onTouchEvent

该方法在View中实现,当然你也可以在子类中重写该方法。为了更好的理解onTouchEvent中对手势的处理规则。我们需要借助如下图:

View图

图中A为根布局容器,B是依赖于A的子布局容器,C是B中的子View,三者的位置关系是A->B->C。
  关于处理规则需要注意两点:

  • 多个View间的onTouchEvent执行顺序
      当在ViewGroup中存在多个View或ViewGroup叠加显示时,gesture事件将会以自上而下的顺序来执行,即最靠近屏幕的C先执行onTouchEvent方法,然后依次向下传递。即C->B->A

  • 返回Ture还是False:
      onTouchEvent是带boolean型的返回参数,其返回值的意义在于是否消耗并处理该事件。在一个完整的gesture事件序列中,手势会从DOWN事件开始,如果在onTouchEvent中返回的true,那么该gesture的余下手势事件都会被该View处理消耗,不再向下传递相关事件。而当onTouchEvent在DOWN事件中返回了false,即表示不关心该gesture事件序列,那么该View将不会接收到剩余的其它手势事件,并将其传递给下一个View进行处理。官方文档中给出的说明如下:

True if the event was handled, false otherwise.

onInterceptTouchEvent

上面说到onTouchEvent是至上而下传递的,靠近屏幕的View拥有处理手势事件的高优先级,那么有没有方法改变这种优先级顺序呢?比如图上B和C同时在DOWN事件中返回了ture,如何将事件分配给B而不是在最顶层的C。ViewGroup中提供了onInterceptTouchEvent方法,通过该方法,我们可以在onTouchEvent方法被调用之前去拦截该手势事件,拦截后的事件会被分配到该View下的onTouchEvent方法中去处理。与onTouchEvent相反,该方法的手势事件传递过程是自下而上,也就是从根View开始传递到上层的子View。同时在gesture事件序列中,所有的手势事件都可以通过onInterceptTouchEvent方法被拦截,这样对于手势的处理有更大的自由度,而不是像onTouchEvent一样局限在DOWN事件下。
  通过onTouchEvent和onInterceptTouchEvent结合使用,手势事件实现了先上后下的一个过程,我们可以通过特定的方法在某个点进行事件的处理。下面总结了一张Down事件在上图中的传递过程的图,该过程中事件不被消耗,完整的被执行。

EventSequence

相关资料

可能是讲解Android事件分发最好的文章
Android View 事件分发机制详解

相关文章

网友评论

      本文标题:View事件分发浅析

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