View 的 dispatchTouchEvent

 /**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        // 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);
        }
        // 如果是down事件,停止嵌套滑动
        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }

        // 安全过滤,本窗口位于非全屏窗口之下时,可能会阻止控件处理触摸事件
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                // 如果事件为鼠标拖动滚动条
                result = true;
            }
            //noinspection SimplifiableIfStatement
            // 只要设置了onTouchListener 和 clickable 可点击 if条件就成立

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            // 若onTouchListener没有消费事件,调用onTouchEvent事件方法
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        // 一致性检验
        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        // 如果是事件序列终止事件,或者是没有消费down事件,终止嵌套滑动
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }
posted @ 2021-03-08 14:50  passerbyzh  阅读(89)  评论(0)    收藏  举报