事件處理機制(二) 一、在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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章