美文网首页
浅谈View的事件分发机制(二)--- 源码分析

浅谈View的事件分发机制(二)--- 源码分析

作者: Elder | 来源:发表于2016-11-26 01:42 被阅读95次

    上一篇介绍了View事件的分发机制以及一些结论,本篇文章将会从源码的角度去进一步分析分发机制。

    一、 Activity点击事件的源码分析

    我们知道当一个点击事件发生时,事件最先传递给当前的Activity,由Activity的dispatchTouchEvent()方法来进行事件的派发。所以我们的切入点就是这个方法,我们看一下这个方法的源码:

    public boolean dispatchTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                onUserInteraction();
            }
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
            return onTouchEvent(ev);
        }
    
    • 第一个调用方法onUserInteraction()可以看一下,它是一个空方法,所以这里不太需要关注它。

    简单查阅了一下上面方法的介绍,这里给大家贴出来,有兴趣的同学可以深入了解一下。
    此方法是activity的方法,当此activity在栈顶时,触屏点击按home,back,menu键等都会触发此方法。下拉statubar、旋转屏幕、锁屏不会触发此方法。所以它会用在屏保应用上,因为当你触屏机器 就会立马触发一个事件,而这个事件又不太明确是什么,正好屏保满足此需求;或者对于一个Activity,控制多长时间没有用户点响应的时候,自己消失等。

    • 我们再来看一下第二个条件,getWindow().superDispatchTouchEvent(ev)等等,什么情况说好的Activity呢。这里我们还需要补充一些知识点,其实Activity的dispatchTouchEvent()方法在分发事件的时候,具体的工作是交由内部的Window来完成的。Window会将事件传递给decor view,这里的decor view一般就是指底层容器(即我们上一篇所提到的setContentView所设置的View的父容器),通过Activity.getWindow.getDecorView()可以获得。一下子蹦出来这么多对象,让我稍后消化一下。
      继续分析源码,第二个条件所调用的方法会将事件传递下去。如果返回true,表示事件已经被消费,条件成立后整个方法也会返回true退出方法。如果返回false,则表示事件没有被消费,所以最后就会调用Activity的onTouchEvent()方法。这也解释了,我们之前得到的结论。Activity的onTouchEvent()方法分析到这,接下来继续点击getWindow().superDispatchTouchEvent(ev)方法,看看Window是如何将事件传递给ViewGroup的。
    public abstract boolean superDispatchTouchEvent(MotionEvent event);
    

    Window类是一个抽象类,这个方法也是一个抽象方法。我们只能找到它的实现子类,看看它是如何实现这个方法的。在Window类的说明中,有这样一句话:

    The only existing implementation of this abstract class is* android.view.PhoneWindow, which you should instantiate when needing a* Window.
    

    好吧这段话就算是我的英语再渣我觉得我也知道我应该去找PhoneWindow这个类。

     // This is the top-level view of the window, containing the window decor.
     private DecorView mDecor;
    
    @Override
    
     public boolean superDispatchTouchEvent(MotionEvent event) {
    
         return mDecor.superDispatchTouchEvent(event);
    
     }
    

    它的实现方法是调用DecorView的superDispatchTouchEvent()方法。是时候解释这三个类之间的关系的时候了。

    这里我也查阅了关于Window类、PhoneWindow类、DecorView的相关资料,这里是原作者的网址:http://www.jianshu.com/p/afa921d8ed24感慨一下互联网时代的好处。

    • Window
      位于 /frameworks/base/core/java/android/view/Window.java。该类是一个抽象类,提供了绘制窗口的一组通用API。可以将之理解为一个载体,各种View在这个载体上显示。

    • PhoneWindow
      位于/frameworks/policies/base/phone/com/android/internal/policy/impl/PhoneWindow.java。该类继承于Window类,是Window类的具体实现,即我们可以通过该类具体去绘制窗口。并且,该类内部包含了一个DecorView对象,该DectorView对象是所有应用窗口(Activity界面)的根View。 简而言之,PhoneWindow类是把一个FrameLayout类即DecorView对象进行一定的包装,将它作为应用窗口的根View,并提供一组通用的窗口操作接口。

    • DecorView
      是PhoneWindow类的内部类。该类是一个FrameLayout的子类,并且是PhoneWindow的子类,该类就是对普通的FrameLayout进行功能的扩展,更确切点可以说是修饰(Decor的英文全称是Decoration,即“修饰”的意思),比如说添加TitleBar(标题栏),以及TitleBar上的滚动条等 。最重要的一点是,它是所有应用窗口的根View 。

    Window类相当于一幅画(抽象概念,什么画我们未知) ,PhoneWindow为一副齐白石先生的山水画(具体概念,我们知道了是谁的、什么性质的画),DecorView则为该山水画的具体内容(有山、有水、有树,各种界面)。DecorView呈现在PhoneWindow上。哇,很棒的比喻啊,一下子三者之间的关系清晰明了了啊。

    简单总结一下,DecorView就是顶级View,我们常见的setContentView()方法中所设置的View是它的子View。我的理解就是它是界面上所有View的根View。以上这些就解释了,事件如何从Activity传送到ViewGroup的。接下来我们继续关注一下ViewGroup的dispatchTouchEvent()方法的分析。

    二、ViewGroup的事件分发

    我们先来看一下方法的实现

    @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);
            }
    
            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) {
                    // 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);
                    resetTouchState();
                }
    
                // Check for interception.
                final boolean intercepted;
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || mFirstTouchTarget != null) {
                    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 {
                    // 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.
                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;
                            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;
                                }
    
                                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);
                                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) {
                    // No touch targets so treat this as an ordinary 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;
                    while (target != null) {
                        final TouchTarget next = target.next;
                        if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                            handled = true;
                        } else {
                            final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                    || intercepted;
                            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;
        }
    

    让我查查这个方法的行数。。。吐血中,没办法结合资料,试着一点点读读。

    • boolean handled = false;初始值为false,也可以看下方法的结尾返回的也是这个变量值,所以这个变量是用来标志该事件是否被消耗的。继续向下看。
    // Check for interception.
                final boolean intercepted;
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || mFirstTouchTarget != null) {
                    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 {
                    // There are no touch targets and this action is not an initial down
                    // so this view group continues to intercept touches.
                    intercepted = true;
                }
    
    • 以上这段代码是用来判断是否拦截事件,可以看到只有当事件是ACTION_DOWN或
      mFirstTouchTarget != null时才会去调用onInterceptTouchEvent()方法来判断是否拦截该事件。条件一很简单理解,条件二到底是什么呢?在上面我找到了它的定义。
    // First touch target in the linked list of touch targets.
        private TouchTarget  mFirstTouchTarget;
    

    通过注释了解到它是一个链表结构,用于存储触碰的目标对象。点击类型时,可以发现它是ViewGroup的一个内部类。

    private static final class TouchTarget {
            private static final int MAX_RECYCLED = 32;
            private static final Object sRecycleLock = new Object[0];
            private static TouchTarget sRecycleBin;
            private static int sRecycledCount;
    
            public static final int ALL_POINTER_IDS = -1; // all ones
    
            // The touched child view.
            public View child;
    
            // The combined bit mask of pointer ids for all pointers captured by the target.
            public int pointerIdBits;
    
            // The next target in the target list.
            public TouchTarget next;
    
            private TouchTarget() {
            }
    
            public static TouchTarget obtain(@NonNull View child, int pointerIdBits) {
                if (child == null) {
                    throw new IllegalArgumentException("child must be non-null");
                }
    
                final TouchTarget target;
                synchronized (sRecycleLock) {
                    if (sRecycleBin == null) {
                        target = new TouchTarget();
                    } else {
                        target = sRecycleBin;
                        sRecycleBin = target.next;
                         sRecycledCount--;
                        target.next = null;
                    }
                }
                target.child = child;
                target.pointerIdBits = pointerIdBits;
                return target;
            }
    
            public void recycle() {
                if (child == null) {
                    throw new IllegalStateException("already recycled once");
                }
    
                synchronized (sRecycleLock) {
                    if (sRecycledCount < MAX_RECYCLED) {
                        next = sRecycleBin;
                        sRecycleBin = this;
                        sRecycledCount += 1;
                    } else {
                        next = null;
                    }
                    child = null;
                }
            }
        }
    

    我们再次看看条件二的语句mFirstTouchTarget != null,所以此时我觉得找到它被赋值的地方将会非常重要。查看了内部类的代码, public static TouchTarget obtain(@NonNull View child, int pointerIdBits);一定是某个地方使用了这个静态方法,给我们的mFirstTouchTarget变量进行了赋值。好继续寻找。

     /**
         * Adds a touch target for specified child to the beginning of the list.
         * Assumes the target child is not already present.
         */
        private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
            final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
            target.next = mFirstTouchTarget;
            mFirstTouchTarget = target;
            return target;
        }
    

    我们发现上面的方法,给我们的变量进行了赋值,那哪里又调用了addTouchTarget()这个方法的呢。我们会发现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;
                                }
    

    看到这我们的逻辑好像清晰了一些,mFirstTouchTarget对象指向的是接受触摸事件的View所组成的链表的起始节点。再次回到我们之前的代码位置。

    // Check for interception.
                final boolean intercepted;
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || mFirstTouchTarget != null) {
                    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 {
                    // There are no touch targets and this action is not an initial down
                    // so this view group continues to intercept touches.
                    intercepted = true;
                }
    

    所以也就是说,当事件由ViewGroup传递给子元素成功处理时,mFirstTouchTarget对象就会被赋值,换种方式来说,也就是说当ViewGroup不拦截事件传递,mFirstTouchTarget!=null。如果拦截事件,mFirstTouchTarget!=null就不成立。此时如果事件序列中的ACTION_MOVE、ACTION_UP事件再传递过来时,由于(actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)条件为false,就不会再调用onInterceptTouchEvent()方法,是否被拦截的标志变量也会设置为intercepted = true,并且后续同一事件序列的其他事件都会默认交给它处理。

    这里还有一种特殊情况,那就是FLAG_DISALLOW_INTERCEPT标记位,这个标记位是通过requestDisallowInterceptTouchEvent()方法来设置的。FLAG_DISALLOW_INTERCEPT这个标记位一旦设置后,ViewGroup就无法拦截除ACTION_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);
                    resetTouchState();
    

    重点观察resetTouchState();方法,代码如下:

    /**
         * Resets all touch state in preparation for a new cycle.
         */
        private void resetTouchState() {
            clearTouchTargets();
            resetCancelNextUpFlag(this);
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
            mNestedScrollAxes = SCROLL_AXIS_NONE;
        }
    
    /**
         * Clears all touch targets.
         */
        private void clearTouchTargets() {
            TouchTarget target = mFirstTouchTarget;
            if (target != null) {
                do {
                    TouchTarget next = target.next;
                    target.recycle();
                    target = next;
                } while (target != null);
                mFirstTouchTarget = null;
            }
        }
    

    可以看到如果传递的事件为ACTION_DOWN,方法就会调用清理和重置状态的一些列方法。导致子View中设置这个标志位无效。而且我们知道只要事件为ACTION_DOWN我们判断是否调用拦截方的条件就成立,就会去调用拦截事件的方法。这里还要重点强调一下,重置状态时会将mFirstTouchTarget赋值为null。

    到这里我们总结一下我们已经分析的这段代码。onInterceptTouchEvent()方法不是每次事件都会调用,如果我们想提前处理所有的点击事件,要选择dispatchTouchEvent()方法,只有这个方法能保证每次都会调用。

    接下来再来观察当ViewGroup不再拦截事件的时候,事件向下分发交由它的子View进行处理是如何实现的,代码如下:

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

    以上代码首先遍历所有子View,然后判断子元素是否能够接受到点击事件,如果能够接受到点击事件,将它加入到接受点击事件View的链表中。判断能否接受到事件的两个条件:

    • 子元素是否在播动画;采用该方法判断canViewReceivePointerEvents(child),代码如下:
    private static boolean canViewReceivePointerEvents(@NonNull View child) {
            return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                    || child.getAnimation() != null;
        }
    
    • 点击事件的坐标是否落在子元素的区域内。采用该方法判断isTransformedTouchPointInView(float x, float y, View child, PointF outLocalPoint);,代码如下:
     protected boolean isTransformedTouchPointInView(float x, float y, View child,
                PointF outLocalPoint) {
            final float[] point = getTempPoint();
            point[0] = x;
            point[1] = y;
            transformPointToViewLocal(point, child);
            final boolean isInView = child.pointInView(point[0], point[1]);
            if (isInView && outLocalPoint != null) {
                outLocalPoint.set(point[0], point[1]);
            }
            return isInView;
        }
    

    上面的代码中if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))它的方法内部实际是调用了子元素的dispatchTouchEvent()方法。代码如下:

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

    如果子元素的dispatchTouchEvent()返回true,条件即成立mFirstTouchTarget就会被赋值同时跳出for循环。代码如下:

    newTouchTarget = addTouchTarget(child, idBitsToAssign);
    alreadyDispatchedToNewTouchTarget = true;
    break;
    

    如果条件不成立,ViewGroup就会把事件分发给下一个元素。如果遍历所有的子元素后事件都没有被合适地处理,这包含了两种情况:

    • ViewGroup没有子元素;
    • 子元素处理了点击事件,但它的dispatchTouchEvent()方法返回了false,这一般都是因为子元素的onTouchEvent()方法返回了false导致的。

    这两种情况下,ViewGroup会自己处理点击事件。代码如下:

    // Dispatch to touch targets.
                if (mFirstTouchTarget == null) {
                    // No touch targets so treat this as an ordinary view.
                    handled = dispatchTransformedTouchEvent(ev, canceled, null,
                            TouchTarget.ALL_POINTER_IDS);
    

    依然会调用dispatchTransformedTouchEvent()这个方法,只不过第三个参数传入的是null。

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

    如果child为null,则它就会调用super.dispatchTouchEvent(event);这个方法,ViewGroup的父类当然是View,所以点击事件开始交由View来处理。

    以上就是Activity将事件传递到ViewGroup以及ViewGroup再将事件传递给View的源码分析。下一篇文章我将和大家继续学习View中事件是如何传递和处理的。通过这样技术文章的学习和书写对自己领会机制的运行真的受益很多,希望自己即将到来的面试能够顺利~~~

    相关文章

      网友评论

          本文标题:浅谈View的事件分发机制(二)--- 源码分析

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