事件處理機(jī)制(二)

Android知識(shí)總結(jié)

一、在ViewGroup 事件分發(fā)

ViewGroup#dispatchTouchEvent 分發(fā)事件

    public boolean dispatchTouchEvent(MotionEvent ev) {
         //驗(yàn)證事件是否連續(xù)
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
        // 殘障人事的輔助類,智能聊天
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }
        //這個(gè)變量用于記錄事件是否被處理完
        boolean handled = false;
        //過濾掉一些不合法的事件:當(dāng)前的View的窗口被遮擋了
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            //重置前面為0 ,只留下后八位,用于判斷相等時(shí)候,可以提高性能。
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            // 多指還單指,只會(huì)執(zhí)行一次 -- Action_point_donw
            // 重置狀態(tài)
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }
            /***********************************第一塊, 檢測(cè)是否攔截*******************************/
            // Check for interception.
            // 檢測(cè)是否攔截 -- 父容器的權(quán)利
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //判斷允不允許這個(gè)View攔截,在內(nèi)部攔截中子View請(qǐng)求 requestDisallowInterceptTouchEvent
                //使用與運(yùn)算作為判斷,可以讓我們?cè)趂lag中,存儲(chǔ)好幾個(gè)標(biāo)志
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                // disallowIntercept 決定 onInterceptTouchEvent 會(huì)不會(huì)執(zhí)行
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                  //重新恢復(fù)Action,以免action在上面的步驟被人為地改變了
                    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);
            }

            //如果viewFlag被設(shè)置了PFLAG_CANCEL_NEXT_UP_EVENT ,那么就表示,下一步應(yīng)該是Cancel事件
            //或者如果當(dāng)前的Action為取消,那么當(dāng)前事件應(yīng)該就是取消了。
            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;
            // 默認(rèn)情況為true -- 是否可以多指
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
                    && !isMouseEvent;
            //新的觸摸對(duì)象,
            TouchTarget newTouchTarget = null;
            //是否把事件分配給了新的觸摸
            boolean alreadyDispatchedToNewTouchTarget = false;
            /************************第二塊, 遍歷子View,詢問子View是否處理事件*******************/
            // 在 if 中分發(fā)事件
            if (!canceled && !intercepted) {
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                // 第一根手指按下時(shí),命中if
                if (actionMasked == MotionEvent.ACTION_DOWN
                        // 第二根或n根手指按下,命中if
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        // 鼠標(biāo)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    // 如果事件是 MotionEvent.ACTION_DOWN,actionIndex = 0
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    // 手指的id ,最多識(shí)別多少手指?32位,位運(yùn)算,一位表示一個(gè)手指,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);

                    // 有多少個(gè)子孩子
                    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 進(jìn)行排序
                        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);

                            // 是否能處理點(diǎn)擊事件
                            // 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;
                            }
                            //如果子View不在之前的觸摸目標(biāo)列表中,
                            //先重置childView的標(biāo)志,去除掉CACEL的標(biāo)志
                            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();
                                // 創(chuàng)建了 newTouchTarget == mFirstTouchTarget
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                // 后面會(huì)子View處理事件用到
                                alreadyDispatchedToNewTouchTarget = true;
                                // 退出循環(huán),不再循環(huán)其他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();
                    }
                    //如果newTouchTarget為null,就代表,這個(gè)事件沒有找到子View去處理它,
                    //那么,如果之前已經(jīng)有了觸摸對(duì)象(比如,我點(diǎn)了一張圖,另一個(gè)手指在外面圖的外面點(diǎn)下去)
                    //那么就把這個(gè)之前那個(gè)觸摸目標(biāo)定為第一個(gè)觸摸對(duì)象,并且把這個(gè)觸摸(pointer)分配給最近添加的觸摸目標(biāo)
                    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處理事件的時(shí)候
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                // 詢問自己是否處理
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // 有子View處理了事件
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                // while循環(huán)為單指操作時(shí)  只會(huì)執(zhí)行一次
                while (target != null) {
                    // 單指操作 next = null
                    final TouchTarget next = target.next;
                    // if命中,直接返回 handle,不作處理。(根據(jù)局部變量 alreadyDispatchedToNewTouchTarget 
                    //確認(rèn)只有Action_Down才能命中
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else { //其他Action 執(zhí)行,如:Action_Move
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        // 詢問 target.child(前面保存的之View)
                        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;
                            }
                             //回收內(nèi)存
                            target.recycle();
                            //把下一個(gè)賦予現(xiàn)在
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }

            // 遇到了取消事件、或者是單點(diǎn)觸摸下情況下手指離開,我們就要更新觸摸的狀態(tài)
            if (canceled
                    || actionMasked == MotionEvent.ACTION_UP
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                //如果是多點(diǎn)觸摸下的手指抬起事件,就要根據(jù)idBit從TouchTarget中移除掉對(duì)應(yīng)的Pointer(觸摸點(diǎn))
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }
    //參數(shù) disallowIntercept 為 true 讓parent 不攔截
    //參數(shù) disallowIntercept 為 fslse 讓parent 攔截
    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }

        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }

        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }

可見ViewGroup#dispatchTouchEvent分為三部分

  • 1、是否攔截子View,intercepted為true攔截,為false 不攔截
  • 2、遍歷子View,詢問子View是否處理事件
  • 3、如果子View都不處理,詢問自己是否處理事件

1.1、 取消事件和重置狀態(tài)

  • 執(zhí)行取消事件
    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);
                // 執(zhí)行取消事件
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            // 清除 TouchTarget
            clearTouchTargets();

            if (syntheticEvent) {
                event.recycle();
            }
        }
    }
  • 重置狀態(tài)
    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;
    }

我們?cè)谧远xView 里面可以重寫這個(gè)方法來處理攔截事件

1.3、詢問子View是否處理事件

在里面會(huì)對(duì)子View 根據(jù)懸浮層進(jìn)行排序

    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];
            // 默認(rèn)不設(shè)置,則為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();
        //當(dāng)取消事件會(huì)執(zhí)行這里,內(nèi)部攔截也會(huì)走
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            //把事件先設(shè)為 ACTION_CANCEL
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            //設(shè)至回原來的事件
            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) {
        // 最前面這一段就是判斷當(dāng)前事件是否能獲得焦點(diǎn),如果不能獲得焦點(diǎn)或者不存在一個(gè)View,
        // 那我們就直接返回False跳出循環(huán)
        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);
        }
        //設(shè)置返回的默認(rèn)值,判斷時(shí)間是否消費(fèi)
        boolean result = false;
        //這段是系統(tǒng)調(diào)試方面,可以直接忽略
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }
        //Android用一個(gè)32位的整型值表示一次TouchEvent事件,低8位表示touch事件的具體動(dòng)作,
        // 比如按下,抬起,滑動(dòng),還有多點(diǎn)觸控時(shí)的按下,抬起,這個(gè)和單點(diǎn)是區(qū)分開的,下面看具體的方法:
        //1 getAction:觸摸動(dòng)作的原始32位信息,包括事件的動(dòng)作,觸控點(diǎn)信息
        //2 getActionMasked:觸摸的動(dòng)作,按下,抬起,滑動(dòng),多點(diǎn)按下,多點(diǎn)抬起
        //3 getActionIndex:觸控點(diǎn)信息
        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // 當(dāng)我們手指按到View上時(shí),其他的依賴滑動(dòng)都要先停下
            stopNestedScroll();
        }
        //過濾掉一些不合法的事件,比如當(dāng)前的View的窗口被遮擋了。
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //ListenerInfo 是view的一個(gè)內(nèi)部類 里面有各種各樣的listener
            ListenerInfo li = mListenerInfo;
            //判斷是否執(zhí)行 OnTouch 事件
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                //事件消費(fèi)
                result = true;
            }
            //onTouch 返回 false 執(zhí)行,即事件沒有消費(fèi)
            if (!result && onTouchEvent(event)) {
                //事件消費(fèi)
                result = true;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        
        // 如果這是手勢(shì)的結(jié)尾,則在嵌套滾動(dòng)后清理
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

接下來看View#onTouchEvent判斷是否消費(fèi)

    public boolean onTouchEvent(MotionEvent event) {
        // 獲取動(dòng)作點(diǎn)擊屏幕的位置坐標(biāo)
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();
        //如果當(dāng)前View是一個(gè)DISABLED狀態(tài),且當(dāng)前View是一個(gè)可點(diǎn)擊或者是可長(zhǎng)按的狀態(tài)
        // 則clickable返回true。表示當(dāng)前事件在此消耗且不做處理
        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
        //如果當(dāng)前View狀態(tài)為DISABLED
        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            //如果View的狀態(tài)是被按壓過,且當(dāng)抬起事件產(chǎn)生,重置View狀態(tài)為未按壓,刷新Drawable的狀態(tài)
            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;
        }
        // 如果設(shè)置了觸摸代理
        if (mTouchDelegate != null) {
            //就交給mTouchDelegate.onTouchEvent處理,如果返回true,則事件被處理了,則不會(huì)向下傳遞
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
        //如果當(dāng)前View的狀態(tài)是可點(diǎn)擊或者是可長(zhǎng)按的,就對(duì)事件流進(jìn)行細(xì)節(jié)處理
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    //如果是抬起的手勢(shì)
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    //清除各種狀態(tài)
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    //prepressed指的是,如果view包裹在一個(gè)scrolling View中,可能會(huì)進(jìn)行滑動(dòng)處理,
                    // 所以設(shè)置了一個(gè)prePress的狀態(tài)
                    //大致是等待一定時(shí)間,然后沒有被父類攔截了事件,則認(rèn)為是點(diǎn)擊到了當(dāng)前的view,從而顯示點(diǎn)擊態(tài)
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    //如果是pressed狀態(tài)或者是prepressed狀態(tài),才進(jìn)行處理
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // 如果設(shè)定了獲取焦點(diǎn),那么調(diào)用requestFocus獲得焦點(diǎn)
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }
                        ////在釋放之前給用戶顯示View的prepressed的狀態(tài),狀態(tài)需要改變?yōu)镻RESSED,
                        // 并且需要將背景變?yōu)榘聪碌臓顟B(tài)為了讓用戶感知到
                        if (prepressed) {
                            setPressed(true, x, y);
                        }
                        //是否處理過長(zhǎng)按操作了,如果是,則直接返回
                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // 如果不是長(zhǎng)按的話,僅僅是一個(gè)Tap,所以移除長(zhǎng)按的回調(diào)
                            //因?yàn)闆]有收到長(zhǎng)按事件的延時(shí)回調(diào)信息,所以這個(gè)事件是onClick事件
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                //UI子線程去執(zhí)行click,為了讓click事件開始的時(shí)候其他視覺發(fā)生變化不影響。
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                //如果post消息失敗,直接調(diào)用處理click事件
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }

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

                        if (prepressed) {
                            //ViewConfiguration.getPressedStateDuration() 獲得的是按下效果顯示的時(shí)間
                            //由PRESSED_STATE_DURATION常量指定,目的是讓用戶感知到click的效果
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // 如果通過post(Runnable runnable)方式調(diào)用失敗,則直接調(diào)用
                            mUnsetPressedState.run();
                        }
                        //移除Tap的回調(diào) 重置View的狀態(tài)
                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    //如果是按下的手勢(shì)
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    //在觸摸事件中執(zhí)行按鈕相關(guān)的動(dòng)作,如果返回true則表示已經(jīng)消耗了down
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        //僅在View支持長(zhǎng)按時(shí)執(zhí)行有效,否則直接退出方法
                        checkForLongClick(
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        break;
                    }
                    //處理如鼠標(biāo)的右鍵的
                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    //判斷當(dāng)前view是否是在滾動(dòng)器當(dāng)中
                    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的狀態(tài)變?yōu)镻REPRESSED,檢測(cè)是Tap還是長(zhǎng)按事件
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        //如果是在滾動(dòng)器當(dāng)中,在滾動(dòng)器當(dāng)中的話延遲返回事件,
                        // 延遲時(shí)間為 ViewConfiguration.getTapTimeout()=100毫秒
                        //在給定的tapTimeout時(shí)間之內(nèi),用戶的觸摸沒有移動(dòng),就當(dāng)作用戶是想點(diǎn)擊,而不是滑動(dòng).
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        //長(zhǎng)按事件的延時(shí)回調(diào),最終決定是否是長(zhǎng)按事件
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(
                                // 長(zhǎng)按事件處理,=< 29 延時(shí)500ms,>29 延時(shí) 400ms
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    //接收到系統(tǒng)發(fā)出的ACTION_CANCLE事件時(shí),重置狀態(tài), 將所有的狀態(tài)設(shè)置為最初始
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        //將實(shí)時(shí)位置傳遞給背景(前景)圖片
                        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)) {
                            // 移除長(zhǎng)按事件
                            removeLongPressCallback();
                            long delay = (long) (ViewConfiguration.getLongPressTimeout()
                                    * mAmbiguousGestureMultiplier);  //長(zhǎng)按事件的延時(shí)延長(zhǎng)一倍
                            delay -= event.getEventTime() - event.getDownTime();
                            checkForLongClick(  //重新計(jì)算長(zhǎng)按的延時(shí)時(shí)間
                                    delay,
                                    x,
                                    y,
                                    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        }
                        touchSlop *= mAmbiguousGestureMultiplier;
                    }

                    // 判斷當(dāng)前滑動(dòng)事件是否還在當(dāng)前view當(dāng)中,不是就執(zhí)行下面的方法
                    //在里面決定移除view后,這個(gè)view不會(huì)響應(yīng)onClick事件的原因
                    if (!pointInView(x, y, touchSlop)) {
                        // 移除PREPRESSED狀態(tài)和對(duì)應(yīng)回調(diào)s
                        removeTapCallback();
                        removeLongPressCallback(); //移除長(zhǎng)按事件
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            //是PRESSED就移除長(zhǎng)按檢測(cè),并移除PRESSED狀態(tài)
                            //設(shè)置 false 后在 UP事件中就不會(huì)執(zhí)行  PerformClick的onClick事件了
                            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 執(zhí)行的位置和關(guān)系

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });
        btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //當(dāng)返回 true, onClick不會(huì)執(zhí)行
                //當(dāng)返回 false, onClick會(huì)執(zhí)行
                return false;
            }
        });

事件關(guān)系
當(dāng) onTouch 返回 true, onClick不會(huì)執(zhí)行
當(dāng) onTouch 返回 false, onClick會(huì)執(zhí)行

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停止?jié)L動(dòng)
            stopNestedScroll();
        }

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //ListenerInfo  里面存儲(chǔ)初始化的事件
            ListenerInfo li = mListenerInfo;
            //ListenerInfo , mOnTouchListener  非空?qǐng)?zhí)行 onTouch 事件
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                     //執(zhí)行 onTouch 事件
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            //短路與,當(dāng)result 為true ,onTouchEvent不執(zhí)行
            //在 onTouchEvent 里面會(huì)處理 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;
    }

執(zhí)行點(diǎn)擊事件,調(diào)用View的內(nèi)部類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事件中處理點(diǎn)擊事件的

case MotionEvent.ACTION_UP:
        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
        if ((viewFlags & TOOLTIP) == TOOLTIP) {
            handleTooltipUp();
        }
        if (!clickable) {
            //清除各種狀態(tài)
            removeTapCallback();
            removeLongPressCallback();
            mInContextButtonPress = false;
            mHasPerformedLongPress = false;
            mIgnoreNextUpEvent = false;
            break;
        }
//prepressed指的是,如果view包裹在一個(gè)scrolling View中,
//可能會(huì)進(jìn)行滑動(dòng)處理,所以設(shè)置了一個(gè)prePress的狀態(tài)
//大致是等待一定時(shí)間,然后沒有被父類攔截了事件,
//則認(rèn)為是點(diǎn)擊到了當(dāng)前的view,從而顯示點(diǎn)擊態(tài)
        boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
        if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
            // 如果設(shè)定了獲取焦點(diǎn),那么調(diào)用requestFocus獲得焦點(diǎn)
            boolean focusTaken = false;

            if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                focusTaken = requestFocus();
            }
//在釋放之前給用戶顯示View的prepressed的狀態(tài),狀態(tài)需要改變?yōu)镻RESSED,
//并且需要將背景變?yōu)榘聪碌臓顟B(tài)為了讓用戶感知到
            if (prepressed) {
                setPressed(true, x, y);
            }

            if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                //如果不是長(zhǎng)按的話,僅僅是一個(gè)Tap,所以移除長(zhǎng)按的回調(diào)
                removeLongPressCallback();

                // Only perform take click actions if we were in the pressed state
                if (!focusTaken) {
                    // UI子線程去執(zhí)行click,為了讓click事件開始的時(shí)候其他視覺發(fā)生變化不影響
                    if (mPerformClick == null) {
                        mPerformClick = new PerformClick();
                    }
                    //如果post消息失敗,直接調(diào)用處理click事件
                    if (!post(mPerformClick)) {
                        performClickInternal();
                    }
                }
            }

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

            if (prepressed) {
 //ViewConfiguration.getPressedStateDuration() 獲得的是按下效果顯示的時(shí)間,
//由PRESSED_STATE_DURATION = 64 常量指定,單位為毫秒
//目的是讓用戶感知到click的效果
                postDelayed(mUnsetPressedState,
                        ViewConfiguration.getPressedStateDuration());
            } else if (!post(mUnsetPressedState)) {
//如果通過post(Runnable runnable)方式調(diào)用失敗,則直接調(diào)用
                mUnsetPressedState.run();
            }
            //移除Tap的回調(diào) 重置View的狀態(tài)
            removeTapCallback();
        }
        mIgnoreNextUpEvent = false;
        break;

post 方法中發(fā)送消息

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

點(diǎn)擊事件最終在View#performClick()方法中執(zhí)行

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

        return result;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容