事件处理机制(二) 一、在ViewGroup 事件分发 二、在View中 事件处理 三、onTouch 和 onClick 执行的位置和关系

Android知识总结

一、在ViewGroup 事件分发

ViewGroup#dispatchTouchEvent 分发事件

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
        // 残障人事的辅助类,智能聊天
        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.
            // 多指还单指,只会执行一次 -- Action_point_donw
            // 重置状态
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }
            /***********************************第一块, 检测是否拦截*******************************/
            // Check for interception.
            // 检测是否拦截 -- 父容器的权利
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                // disallowIntercept 决定 onInterceptTouchEvent 会不会执行
                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 isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
            // 默认情况为true -- 是否可以多指
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
                    && !isMouseEvent;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            /************************第二块, 遍历子View,询问子View是否处理事件*******************/
            // 在 if 中分发事件
            if (!canceled && !intercepted) {
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                // 第一根手指按下时,命中if
                if (actionMasked == MotionEvent.ACTION_DOWN
                        // 第二根或n根手指按下,命中if
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        // 鼠标
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    // 如果事件是 MotionEvent.ACTION_DOWN,actionIndex = 0
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    // 手指的id ,最多识别多少手指?32位,位运算,一位表示一个手指,0000000000111
                    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 =
                                isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
                        final float y =
                                isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        // 将子View 进行排序
                        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);

                            // 是否能处理点击事件
                            // view是否可见或者animotion不为空
                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }

                            // 单指操作,为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.
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
                            // 询问 child 是否处理事件,如果child处理,则命中if -- 递归
                            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 == mFirstTouchTarget
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                // 后面会用到
                                alreadyDispatchedToNewTouchTarget = true;
                                // 退出循环,不再循环其他child
                                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;
                    }
                }
            }

            /************************第三块, 判断子View处理还是自己处理事件*******************/
            // Dispatch to touch targets.
            // 没有child处理事件的时候
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                // 询问自己是否处理
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // 有子View处理了事件
                // 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循环为单指操作时  只会执行一次
                while (target != null) {
                    // 单指操作 next = null
                    final TouchTarget next = target.next;
                    // if命中,直接返回 handle,不作处理
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        // 询问 target.child(前面保存的)
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        // 为true 取消child处理事件
                        if (cancelChild) {
                            if (predecessor == null) {
                                // mFirstTouchTarget 置为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;
    }

可见ViewGroup#dispatchTouchEvent分为三部分

  • 1、是否拦截子View,intercepted为true拦截,为false 不拦截
  • 2、遍历子View,询问子View是否处理事件
  • 3、如果子View都不处理,询问自己是否处理事件

1.1、 取消事件和重置状态

  • 执行取消事件
    private void cancelAndClearTouchTargets(MotionEvent event) {
        if (mFirstTouchTarget != null) {
            boolean syntheticEvent = false;
            if (event == null) {
                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;
            }

            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
                resetCancelNextUpFlag(target.child);
                // 执行取消事件
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            // 清除 TouchTarget
            clearTouchTargets();

            if (syntheticEvent) {
                event.recycle();
            }
        }
    }
  • 重置状态
    private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        // 重置了 mGroupFlags 的值
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }

1.2、拦截事件

    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 里面可以重写这个方法来处理拦截事件

1.3、询问子View是否处理事件

在里面会对子View 根据悬浮层进行排序

    public ArrayList<View> buildTouchDispatchChildList() {
        return buildOrderedChildList();
    }
    ArrayList<View> buildOrderedChildList() {
        final int childrenCount = mChildrenCount;
        if (childrenCount <= 1 || !hasChildWithZ()) return null;

        if (mPreSortedChildren == null) {
            mPreSortedChildren = new ArrayList<>(childrenCount);
        } else {
            // callers should clear, so clear shouldn't be necessary, but for safety...
            mPreSortedChildren.clear();
            mPreSortedChildren.ensureCapacity(childrenCount);
        }

        final boolean customOrder = isChildrenDrawingOrderEnabled();
        for (int i = 0; i < childrenCount; i++) {
            // add next child (in child order) to end of list
            final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
            final View nextChild = mChildren[childIndex];
            // 默认不设置,则为0
            final float currentZ = nextChild.getZ();

            // insert ahead of any Views with greater Z
            int insertIndex = i;
            while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) {
                insertIndex--;
            }
            // xml中布局 靠后的,放在集合后面
            mPreSortedChildren.add(insertIndex, nextChild);
        }
        return mPreSortedChildren;
    }
    private int getAndVerifyPreorderedIndex(int childrenCount, int i, boolean customOrder) {
        final int childIndex;
        if (customOrder) {
            final int childIndex1 = getChildDrawingOrder(childrenCount, i);
            if (childIndex1 >= childrenCount) {
                throw new IndexOutOfBoundsException("getChildDrawingOrder() "
                        + "returned invalid index " + childIndex1
                        + " (child count is " + childrenCount + ")");
            }
            childIndex = childIndex1;
        } else {
            childIndex = i;
        }
        return childIndex;
    }

1.4、询问子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();
        //当取消事件会执行这里,内部拦截也会走
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            //把事件先设为 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;
        }

        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) {
            // View.dispatchTouchEvent(处理事件)
            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());
            }

            // child是容器,ViewGroup.dispatchTouchEvent;child是View,View.dispatchTouchEvent(处理事件)
            handled = child.dispatchTouchEvent(transformedEvent);
        }

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

二、在View中 事件处理

    public boolean dispatchTouchEvent(MotionEvent event) {
        // 最前面这一段就是判断当前事件是否能获得焦点,如果不能获得焦点或者不存在一个View,
        // 那我们就直接返回False跳出循环
        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);
        }
        //Android用一个32位的整型值表示一次TouchEvent事件,低8位表示touch事件的具体动作,
        // 比如按下,擡起,滑动,还有多点触控时的按下,擡起,这个和单点是区分开的,下面看具体的方法:
        //1 getAction:触摸动作的原始32位信息,包括事件的动作,触控点信息
        //2 getActionMasked:触摸的动作,按下,擡起,滑动,多点按下,多点擡起
        //3 getActionIndex:触控点信息
        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // 当我们手指按到View上时,其他的依赖滑动都要先停下
            stopNestedScroll();
        }
        //过滤掉一些不合法的事件,比如当前的View的窗口被遮挡了。
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //ListenerInfo 是view的一个内部类 里面有各种各样的listener
            ListenerInfo li = mListenerInfo;
            //判断是否执行 OnTouch 事件
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                //事件消费
                result = true;
            }
            //onTouch 返回 false 执行,即事件没有消费
            if (!result && onTouchEvent(event)) {
                //事件消费
                result = true;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        
        // 如果这是手势的结尾,则在嵌套滚动后清理
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

接下来看View#onTouchEvent判断是否消费

    public boolean onTouchEvent(MotionEvent event) {
        // 获取动作点击屏幕的位置座标
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();
        //如果当前View是一个DISABLED状态,且当前View是一个可点击或者是可长按的状态
        // 则clickable返回true。表示当前事件在此消耗且不做处理
        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
        //如果当前View状态为DISABLED
        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            //如果View的状态是被按压过,且当擡起事件产生,重置View状态为未按压,刷新Drawable的状态
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                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) {
            //就交给mTouchDelegate.onTouchEvent处理,如果返回true,则事件被处理了,则不会向下传递
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
        //如果当前View的状态是可点击或者是可长按的,就对事件流进行细节处理
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    //如果是擡起的手势
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    //清除各种状态
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    //prepressed指的是,如果view包裹在一个scrolling View中,可能会进行滑动处理,
                    // 所以设置了一个prePress的状态
                    //大致是等待一定时间,然后没有被父类拦截了事件,则认为是点击到了当前的view,从而显示点击态
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    //如果是pressed状态或者是prepressed状态,才进行处理
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // 如果设定了获取焦点,那么调用requestFocus获得焦点
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }
                        ////在释放之前给用户显示View的prepressed的状态,状态需要改变为PRESSED,
                        // 并且需要将背景变为按下的状态为了让用户感知到
                        if (prepressed) {
                            setPressed(true, x, y);
                        }
                        //是否处理过长按操作了,如果是,则直接返回
                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // 如果不是长按的话,仅仅是一个Tap,所以移除长按的回调
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                //UI子线程去执行click,为了让click事件开始的时候其他视觉发生变化不影响。
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                //如果post消息失败,直接调用处理click事件
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            //ViewConfiguration.getPressedStateDuration() 获得的是按下效果显示的时间
                            //由PRESSED_STATE_DURATION常量指定,目的是让用户感知到click的效果
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // 如果通过post(Runnable runnable)方式调用失败,则直接调用
                            mUnsetPressedState.run();
                        }
                        //移除Tap的回调 重置View的状态
                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    //如果是按下的手势
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    //在触摸事件中执行按钮相关的动作,如果返回true则表示已经消耗了down
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        //仅在View支持长按时执行有效,否则直接退出方法
                        checkForLongClick(
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        break;
                    }
                    //处理如鼠标的右键的
                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    //判断当前view是否是在滚动器当中
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        //将view的状态变为PREPRESSED,检测是Tap还是长按事件
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        //如果是在滚动器当中,在滚动器当中的话延迟返回事件,
                        // 延迟时间为 ViewConfiguration.getTapTimeout()=100毫秒
                        //在给定的tapTimeout时间之内,用户的触摸没有移动,就当作用户是想点击,而不是滑动.
                        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_CANCEL:
                    //接收到系统发出的ACTION_CANCLE事件时,重置状态, 将所有的状态设置为最初始
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        //将实时位置传递给背景(前景)图片
                        drawableHotspotChanged(x, y);
                    }

                    final int motionClassification = event.getClassification();
                    final boolean ambiguousGesture =
                            motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
                    int touchSlop = mTouchSlop;
                    if (ambiguousGesture && hasPendingLongPressCallback()) {
                        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.
                            removeLongPressCallback();
                            long delay = (long) (ViewConfiguration.getLongPressTimeout()
                                    * mAmbiguousGestureMultiplier);
                            // Subtract the time already spent
                            delay -= event.getEventTime() - event.getDownTime();
                            checkForLongClick(
                                    delay,
                                    x,
                                    y,
                                    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        }
                        touchSlop *= mAmbiguousGestureMultiplier;
                    }

                    // 判断当前滑动事件是否还在当前view当中,不是就执行下面的方法
                    if (!pointInView(x, y, touchSlop)) {
                        // 移除PREPRESSED状态和对应回调s
                        removeTapCallback();
                        removeLongPressCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            //是PRESSED就移除长按检测,并移除PRESSED状态
                            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;
    }

三、onTouch 和 onClick 执行的位置和关系

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });
        btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当返回 true, onClick不会执行
                //当返回 false, onClick会执行
                return false;
            }
        });

事件关系
当 onTouch 返回 true, onClick不会执行
当 onTouch 返回 false, onClick会执行

1.1、源码流程

我们从View的dispatchTouchEvent处事件处理开始分析

    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) {
            // 如果是Down停止滚动
            stopNestedScroll();
        }

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //ListenerInfo  里面存储初始化的事件
            ListenerInfo li = mListenerInfo;
            //ListenerInfo , mOnTouchListener  非空执行 onTouch 事件
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                     //执行 onTouch 事件
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            //短路与,当result 为true ,onTouchEvent不执行
            //在 onTouchEvent 里面会处理 onClick 事件
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // of the gesture.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

执行点击事件,调用View的内部类PerformClick

    private final class PerformClick implements Runnable {
        @Override
        public void run() {
            recordGestureClassification(TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__SINGLE_TAP);
            performClickInternal();
        }
    }
    private boolean performClickInternal() {
        // be interested on.
        notifyAutofillManagerOnClick();
        return performClick();
    }

View#onTouchEvent里面的ACTION_UP事件中处理点击事件的

case MotionEvent.ACTION_UP:
        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
        if ((viewFlags & TOOLTIP) == TOOLTIP) {
            handleTooltipUp();
        }
        if (!clickable) {
            //清除各种状态
            removeTapCallback();
            removeLongPressCallback();
            mInContextButtonPress = false;
            mHasPerformedLongPress = false;
            mIgnoreNextUpEvent = false;
            break;
        }
//prepressed指的是,如果view包裹在一个scrolling View中,
//可能会进行滑动处理,所以设置了一个prePress的状态
//大致是等待一定时间,然后没有被父类拦截了事件,
//则认为是点击到了当前的view,从而显示点击态
        boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
        if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
            // 如果设定了获取焦点,那么调用requestFocus获得焦点
            boolean focusTaken = false;

            if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                focusTaken = requestFocus();
            }
//在释放之前给用户显示View的prepressed的状态,状态需要改变为PRESSED,
//并且需要将背景变为按下的状态为了让用户感知到
            if (prepressed) {
                setPressed(true, x, y);
            }

            if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                //如果不是长按的话,仅仅是一个Tap,所以移除长按的回调
                removeLongPressCallback();

                // Only perform take click actions if we were in the pressed state
                if (!focusTaken) {
                    // UI子线程去执行click,为了让click事件开始的时候其他视觉发生变化不影响
                    if (mPerformClick == null) {
                        mPerformClick = new PerformClick();
                    }
                    //如果post消息失败,直接调用处理click事件
                    if (!post(mPerformClick)) {
                        performClickInternal();
                    }
                }
            }

            if (mUnsetPressedState == null) {
                mUnsetPressedState = new UnsetPressedState();
            }

            if (prepressed) {
 //ViewConfiguration.getPressedStateDuration() 获得的是按下效果显示的时间,
//由PRESSED_STATE_DURATION = 64 常量指定,单位为毫秒
//目的是让用户感知到click的效果
                postDelayed(mUnsetPressedState,
                        ViewConfiguration.getPressedStateDuration());
            } else if (!post(mUnsetPressedState)) {
//如果通过post(Runnable runnable)方式调用失败,则直接调用
                mUnsetPressedState.run();
            }
            //移除Tap的回调 重置View的状态
            removeTapCallback();
        }
        mIgnoreNextUpEvent = false;
        break;

post 方法中发送消息

    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }
        getRunQueue().post(action);
        return true;
    }

点击事件最终在View#performClick()方法中执行

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

        return result;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章