源码 解读事件分发机制

源码角度 解读事件分发

View 的事件分发 (View.dispatchTouchEvent())

1.流程

在这里插入图片描述

2.源码

//View.java
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();
        //1.如果是actionDown
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            //父类停止滑动(嵌套滑动机制)
            stopNestedScroll();
        }
         //2.如果event处于安全策略的条件下
        if (onFilterTouchEventForSecurity(event)) {
            //如果view enable  且鼠标处理的事件为true
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //3.如果 View enable  OnTouchListener 不为null,且mOnTouchListener.onTouch 返回true
            ListenerInfo li = mLi stenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            //4.执行onTouchEvent(event)
            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.
     //如果 up ,cancle ,或者 (actionDown 且没有被消费)
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            //停止parent 滑动
            stopNestedScroll();
        }

        return result;
    }
  1. mOnTouchListener.onTouch() 返回true的时候,onTouch() 并不会执行。
stopNestedScroll()
 public void stopNestedScroll() {
        if (mNestedScrollingParent != null) {
            mNestedScrollingParent.onStopNestedScroll(this);
            mNestedScrollingParent = null;
        }
    }
onTouchEvent(MotionEvent event);
 public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();
     /****************************** part1 **************************************/
        //标志位:是否可以短按,长按,或者上下文点击
        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
          //如果是enable
        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            //如果事件是 actionUp 且处于按下状态
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
               //将按下状态置为false
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }
     
      /********************************************************************/
      //如果代理不为空,则转给代理
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
       //如果可点击的
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {       
                  case MotionEvent.ACTION_DOWN:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;
                    if (!clickable) {
                        checkForLongClick(
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        break;
                    }
                                  ......
                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    //如果在一个滑动容器中,延迟发送一个 mPendingCheckForTap CallBack
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                    }
                    break;
                    
                case MotionEvent.ACTION_UP:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        //不可点击的,移除相关callback
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            //获取焦点
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true, x, y);
                        }
                         //如果没有长按Callback 且不忽略下一个event
                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            //移除长按callback
                            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();
                                }
                                //1.发送点击事件
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }
                        
                        ....省略.....
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_CANCEL:
                    if (clickable) {
                        setPressed(false);
                    }
                    //取消相关callBack
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                             ........
                    final boolean ambiguousGesture =
                            motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
                    int touchSlop = mTouchSlop;
                    //如果有长按callBack
                    if (ambiguousGesture && hasPendingLongPressCallback()) {
                        final float ambiguousMultiplier =
                                ViewConfiguration.getAmbiguousGestureMultiplier();
                        //点击在View 区域内
                        if (!pointInView(x, y, touchSlop)) {
                            // The default action here is to cancel long press. But instead, we
                            // just extend the timeout here, in case the classification
                            // stays ambiguous.
                            //移除长按callBack
                            removeLongPressCallback();
                            long delay = (long) (ViewConfiguration.getLongPressTimeout()
                                    * ambiguousMultiplier);
                            // Subtract the time already spent
                            delay -= event.getEventTime() - event.getDownTime();
                            checkForLongClick(
                                    delay,
                                    x,
                                    y,
                                    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        }
                        touchSlop *= ambiguousMultiplier;
                    }

                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, touchSlop)) {
                        // Outside button
                        // Remove any future long press/tap checks
                        removeTapCallback();
                        removeLongPressCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            setPressed(false);
                        }
                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    }

                    final boolean deepPress =
                            motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
                    if (deepPress && hasPendingLongPressCallback()) {
                        // process the long click action immediately
                        removeLongPressCallback();
                        checkForLongClick(
                                0 /* send immediately */,
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
                    }

                    break;
            }

            return true;
        }

        return false;
    }
1. performClickInternal();
 private final class PerformClick implements Runnable {
        @Override
        public void run() {
               recordGestureClassification(TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__SINGLE_TAP);
            performClickInternal();
        }
    }



private boolean performClickInternal() {
        // Must notify autofill manager before performing the click actions to avoid scenarios where
        // the app has a click listener that changes the state of views the autofill service might
        // be interested on.
        notifyAutofillManagerOnClick();

        return performClick();
    }

 //执行onClickListener
 public boolean performClick() {
        // We still need to call this method to handle the cases where performClick() was called
        // externally, instead of through performClickInternal()
        notifyAutofillManagerOnClick();

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

2.checkForLongClick()
   private void checkForLongClick(long delay, float x, float y, int classification) {
        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
            mHasPerformedLongPress = false;

            if (mPendingCheckForLongPress == null) {
                mPendingCheckForLongPress = new CheckForLongPress();
            }
            mPendingCheckForLongPress.setAnchor(x, y);
            mPendingCheckForLongPress.rememberWindowAttachCount();
            mPendingCheckForLongPress.rememberPressedState();
            mPendingCheckForLongPress.setClassification(classification);
            postDelayed(mPendingCheckForLongPress, delay);
        }
    }

 private final class CheckForLongPress implements Runnable {
        private int mOriginalWindowAttachCount;
        private float mX;
        private float mY;
        private boolean mOriginalPressedState;
        /**
         * The classification of the long click being checked: one of the
         * StatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__* constants.
         */
        private int mClassification;

        @Override
        public void run() {
            if ((mOriginalPressedState == isPressed()) && (mParent != null)
                    && mOriginalWindowAttachCount == mWindowAttachCount) {
                recordGestureClassification(mClassification);
                //如果LongClickListenr 回调返回 true  mHasPerformedLongPress 会置为 true,所以在 ActionUp 时,不会执行clickListener
                if (performLongClick(mX, mY)) {
                    mHasPerformedLongPress = true;
                }
            }
        }

        public void setAnchor(float x, float y) {
            mX = x;
            mY = y;
        }

        public void rememberWindowAttachCount() {
            mOriginalWindowAttachCount = mWindowAttachCount;
        }

        public void rememberPressedState() {
            mOriginalPressedState = isPressed();
        }

        public void setClassification(int classification) {
            mClassification = classification;
        }
    }


 public boolean performLongClick(float x, float y) {
        mLongClickX = x;
        mLongClickY = y;
        final boolean handled = performLongClick();
        mLongClickX = Float.NaN;
        mLongClickY = Float.NaN;
        return handled;
    }

public boolean performLongClick() {
        return performLongClickInternal(mLongClickX, mLongClickY);
    }


 private boolean performLongClickInternal(float x, float y) {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);

        boolean handled = false;
      //执行LongClickListener 回调
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnLongClickListener != null) {
            handled = li.mOnLongClickListener.onLongClick(View.this);
        }
        if (!handled) {
            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
        }
        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
            if (!handled) {
                handled = showLongClickTooltip((int) x, (int) y);
            }
        }
        if (handled) {
            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
        return handled;
    }

总结

  1. **被禁用的可点击view ,仍然可以在onTouch 中接受到事件,只是不响应 **(part1 )
  2. 当View 处于可点击状态时(clickable/longClickable/contextClickable), onTouch 返回 true,消耗事件
  3. OnClickListener 是在 ActionUp 的时候回调。且当OnLongClickListener#OnClick( ) 返回 true的时,mHasPerformedLongPress 置为 true,因此 OnClickListener #OnClick 并不执行。

ViewGoup 事件分发( ViewGroup.dispatchTouchEvent())

TouchTarget:

该对象是一个节点,封装了 可以处理 down,move,up ,cancel 一系列事件的View

 
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.
        @UnsupportedAppUsage
       //绑定的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;

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

    //回收方法,将绑定的view释放,在回收池容量允许的条件下,加入回收池
        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;
            }
        }
    }
1.流程

在这里插入图片描述

2.源码分析
//ViewGroup.java
 //单向链表,存放可以处理一系列事件(down,move,up,cancel)的 touchTarget对象。
  private TouchTarget mFirstTouchTarget;

    public boolean dispatchTouchEvent(MotionEvent ev) {
      boolean handled = false;  
            final int action = ev.getAction();
            //action 是一个32位的数,
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
        //如果是第一个手指的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.
                //1.清除targets
                cancelAndClearTouchTargets(ev);
                //2.重置状态
                resetTouchState();
            }
         
           final boolean intercepted;
              //如果是actionDown 或者 mFirstTouchTarget!=null
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //ViewGroup 的标志状态,是否拒绝拦截
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //3.不拒绝拦截,执行onInterceptTouchEvent
                    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;
            }
        
            .......
                
                      // 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) {
                             .........
                    //单个手指的down事件
                 if (actionMasked == MotionEvent.ACTION_DOWN
                     //split 支持多点触控  且 其它手指 down
                     //split  通过  setMotionEventSplittingEnabled() 可以设置
                        ||(split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {               
                                 
                  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;
                        //倒序遍历所有的childView,对于重叠的子View ,最上面的View 最先接受到事件,所以倒序遍历
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

                          .....
                             //4.如果child 不可以接受事件 或者 不在view的点击区域内
                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
                            //5.找到满足条件的child ,从缓存的touchTarget列表中 获取TouchTarget对象
                            newTouchTarget = getTouchTarget(child);
                            //该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;
                            }
                            //child 设置取消标志
                            resetCancelNextUpFlag(child);
                            //6.child 是否分发了该事件
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                    .........
                                        //7.touchTarget缓存中 添加新的 touchTarget
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                //该标志置为true
                                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();
                        //如果没有找到接受事件的child 且 touchTrarget集合 不为空,则将结合最后一个touchTarget ,赋给newTouchTarget
                       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.
            //6没有接受事件的childView, 则交给了viewGroup 处理(将viewGroup 作为view ,走了view 的事件分发流程)
            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;
                //遍历寻找可以处理事件的target
                while (target != null) {
                    final TouchTarget next = target.next;
                    //如果已经处理了touchTarget(ActionDown) 直接返回
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        //如果已经被拦截
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //将事件传递给 child,如果事件已被 viewGroup 拦截,则 将事件改为cancel事件传给 child  
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        //如果是cancel 事件(包括group拦截条件),将mFirstTarget 头节点(,回收掉。 当下次move 事件传递的时候。
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            //回收target
                            target.recycle();
                            //将target 切换缓存下一个target ,继续遍历
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                     //将target 切换缓存下一个target ,继续遍历
                    target = next;
                }
            }

        
        return handle;
        
    }
6.dispatchTransformedTouchEvent** 分发事件的核心处理方法
  • 判断是否发送cancel 事件
  • 当child 为null,交给viewGroup 进行 作为View 的分发处理,否则交给child View 进行分发
 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();
      //如果满足cancel 条件
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            //action设置成cancel
            event.setAction(MotionEvent.ACTION_CANCEL);
            /***********************mark*******************************/
            if (child == null) {
                //如果child 为null,则调用起View的事件分发(此时ViewGroup 当做了View,调用了父类View的 dispatchTouchEvent )
                handled = super.dispatchTouchEvent(event);
            } else {
                //执行了child的 dispatchTouchEvent 方法
                handled = child.dispatchTouchEvent(event);
            }
              /***********************mark*******************************/
            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;
      //和 上面 Mark 部分一样的处理
        if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    //计算相当于子view 的 坐标
                    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);
        }
         //同上面Mark部分一样的 原理
        // 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;
    }
1.cancelAndClearTouchTargets(); 清除所有touchTarget

  /**
     * Cancels and clears all touch targets.
     */
    private void cancelAndClearTouchTargets(MotionEvent event) {
        if (mFirstTouchTarget != null) {
            boolean syntheticEvent = false;
            if (event == null) {
                //如果event为null,创建一个cancel 事件
                final long now = SystemClock.uptimeMillis();
                event = MotionEvent.obtain(now, now,
                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
                syntheticEvent = true;
            }
            //当mFirstTouchTarget 不为空时,将mFirstTouchTarget 链表中,都发送 cancel 事件
            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
                resetCancelNextUpFlag(target.child);
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            clearTouchTargets();
             //创建的cancel事件回收
            if (syntheticEvent) {
                event.recycle();
            }
        }
    }


 /**
     * Resets the cancel next up flag.
     * Returns true if the flag was previously set.
     */
 //重置下一步取消标志
    private static boolean resetCancelNextUpFlag(@NonNull View view) {
        if ((view.mPrivateFlags & PFLAG_CANCEL_NEXT_UP_EVENT) != 0) {
            view.mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
            return true;
        }
        return false;
    }


 //清除所有TouchTarget
  private void clearTouchTargets() {
        TouchTarget target = mFirstTouchTarget;
        if (target != null) {
            do {
                TouchTarget next = target.next;
                target.recycle();
                target = next;
            } while (target != null);
            mFirstTouchTarget = null;
        }
    }

2. resetTouchState() 重置ViewGroup 标志位
  /**
     * Resets all touch state in preparation for a new cycle.
     */
    private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        //viewGroup 拒绝拦截标志位
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        //viewGroup 嵌套滑动互动方向 为none
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }
3. 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;
        }
      //如果是触摸事件,默认返回false
        return false;
    }
4. 判断view是否可以接受事件
//View.java 
protected boolean canReceivePointerEvents() {
    //当View 处于可见且没有在执行动画的时候,可以接受到事件
        return (mViewFlags & VISIBILITY_MASK) == VISIBLE || getAnimation() != null;
    }
//ViewGroup.java
   //判断事件的坐标,是否在child 的范围内
   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;
    }
//ViewGroup.java
 //将坐标值转换为group中 View 的坐标
   public void transformPointToViewLocal(float[] point, View child) {
        point[0] += mScrollX - child.mLeft;
        point[1] += mScrollY - child.mTop;

        if (!child.hasIdentityMatrix()) {
            child.getInverseMatrix().mapPoints(point);
        }
    }
5.getTouchTarget(child) 查找v缓存中是否有child touchTarget
//遍历mFirstTouchTarget
private TouchTarget getTouchTarget(@NonNull View child) {
       for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next){
            if (target.child == child) {
                return target;
            }
        }
        return null;
    }
7.addTouchTarget()生成child 的target 并加入接受事件的链表中(mFirstTouchTarget)
  private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
      //获取方法,参考最上面的 TouchTarget 分析
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
      //加到表头
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

总结

  1. viewGroup 里面的 TouchTarget 对应了 一根手指 和 一个可以接受到事件的子View
  2. 当接收到的事件是第一根手指的 down 事件时,清空了所有 touchTarget ,重置了ViewGroup 状态 (可以拦截,执行onInterceptTouchEvent() 方法)
  3. 每当接受到手指的down(包括其他手指down) 事件,都会创建一个对应的 TouchTarget
  4. 由于2 的原因,child.requestDisallowInterceptTouchEvent() 只能阻拦 父容器 对 down以后事件的拦截(move,up)
  5. 对于 move ,up 事件,当ViewGroup mFirstTouchTarget为空的 时,直接走 父容器的 View 事件分发。如果 mFirstTouchTarget不为空 条件下,父容器拦截的话,直接将接受的事件置为cancel 发给 mFirstTouchTarget,并将 mFirstTouchTarget 头节点移除。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值