一步步探索學(xué)習(xí)Android Touch事件分發(fā)傳遞機(jī)制(三)

前言

該系列文章分三篇:

  1. 一步步探索學(xué)習(xí)Android Touch事件分發(fā)傳遞機(jī)制(一)
    通過寫demo打Log呜呐,以ACTION_DOWN事件為例绑咱,完整了解整個(gè)Android Touch事件分發(fā)傳遞機(jī)制陆盘。
  1. 一步步探索學(xué)習(xí)Android Touch事件分發(fā)傳遞機(jī)制(二)
    探索了ACTION_MOVE和ACTION_UP事件的分發(fā)傳遞規(guī)律。
  1. 一步步探索學(xué)習(xí)Android Touch事件分發(fā)傳遞機(jī)制(三)
    即本篇厦章,將通過Android源碼分析今野,從本質(zhì)上認(rèn)識(shí)Android Touch事件分發(fā)傳遞機(jī)制。

1. dispatchTouchEvent()方法源碼分析

1.1 Activity的dispatchTouchEvent()方法
  • 源碼:
   /**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //當(dāng)判斷是ACTION_DOWN事件饺鹃,回調(diào)onUserInteraction()
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            //getWindow()方法拿到的是PhoneWindow的實(shí)例
            return true;
        }
        //如果沒有找到消費(fèi)該事件的子View莫秆,最終會(huì)交給Activity的onTouchEvent()處理
        return onTouchEvent(ev);
    }
  • 分析:
    • 該方法首先判斷傳遞進(jìn)來的是不是一個(gè)ACTION_DOWN事件,if 是悔详,就觸發(fā)一個(gè)叫做 onUserInteraction()的回調(diào)方法镊屎。

    • onUserInteraction()方法在Activity.java中是個(gè)空實(shí)現(xiàn)。開發(fā)者可以在需要的時(shí)候重寫它茄螃,比如用于判斷是不是用戶開始做與屏幕交互的事情了杯道。

    • 然后,判斷調(diào)用了getWindow().superDispatchTouchEvent(ev)责蝠。getWindow()拿到的是PhoneWindow的實(shí)例党巾。

    • 這里需要簡(jiǎn)單說明一下Android窗口結(jié)構(gòu):


      Android Window 結(jié)構(gòu)
    • 繼續(xù)看源碼,看看PhoneWindow.java中的superDispatchTouchEvent(ev)方法霜医。

       @Override
          public boolean superDispatchTouchEvent(MotionEvent event) {
              return mDecor.superDispatchTouchEvent(event);
          }
      
    • 可以看到齿拂,這個(gè)方法內(nèi)部又去調(diào)用了DecorView的superDispatchTouchEvent(ev)方法。

    • 一路這么調(diào)用肴敛,DecorView其實(shí)是FrameLayout的子類署海,它沒重寫這個(gè)方法,所以最后調(diào)用到了ViewGroup的dispatchTouchEvent()方法医男。

1.2 ViewGroup的dispatchTouchEvent()方法
  • 源碼:
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        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.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // Throw away all previous state when starting a new touch gesture.
                // The framework may have dropped the up or cancel event for the previous gesture
                // due to an app switch, ANR, or some other state change.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                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 split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) {

                // If the event is targeting accessiiblity focus we give it to the
                // view that has accessibility focus and if it does not handle it
                // we clear the flag and dispatch the event to all children as usual.
                // We are looking up the accessibility focused host to avoid keeping
                // state since these events are very rare.
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    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 = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

                            // If there is a view that has accessibility focus we want it
                            // to get the event first and if not handled we will perform a
                            // normal dispatch. We may do a double iteration but this is
                            // safer given the timeframe.
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }

                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            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);
                            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 = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }

                            // The accessibility focus didn't handle the event, so clear
                            // the flag and do a normal dispatch to all children.
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        // Did not find a child to receive the event.
                        // Assign the pointer to the least recently added target.
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it.  Cancel touch targets if necessary.
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        if (cancelChild) {
                            if (predecessor == 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;
    }
  • 分析:
    • 這個(gè)方法的代碼邏輯比較多砸狞,有兩百多行。我們?nèi)シ本秃?jiǎn)镀梭,理出主要的邏輯就行刀森,畢竟我們只關(guān)心Touch事件的流向和處理邏輯。

    • 首先來看一下报账,ViewGroup的dispatchTouchEvent()方法首先是要判斷該事件自己要不要攔截下來自己處理研底。

    ``` java
         // Check for interception.
                final boolean intercepted;
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || mFirstTouchTarget != null) {
                    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                    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;
                }
    
    ```

- 這里面我們看到一個(gè)很關(guān)鍵的boolean變量***disallowIntercept***,這個(gè)變量是控制是不是不允許父控件去攔截該事件的透罢,取值是看***mGroupFlags**的取值*榜晦。

> 這里面涉及到一個(gè)方法:***requestDisallowInterceptTouchEvent()***方法。這個(gè)方法確定***mGroupFlags**的取值*羽圃,控制請(qǐng)求父布局不攔截該事件乾胶,而是交給自己去做處理。這個(gè)方法在處理滑動(dòng)沖突等場(chǎng)景時(shí)經(jīng)常用到。但在這里為了整個(gè)源碼分析的邏輯簡(jiǎn)潔清晰识窿,不再具體分析該方法的代碼斩郎。

- 還有大家可以注意到一個(gè)判斷條件:  ***if (actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null)***,也就是說ViewGroup去判斷這個(gè)事件該不該去攔截腕扶,首先是這個(gè)事件得是ACTION_DOWN事件或者該事件的mFirstTouchTarget(目標(biāo)子View)是不為空的才會(huì)考慮要不要攔截孽拷。

- ***這說明mFirstTouchTarget為空的情況下,ACTION_MOVE和ACTION_UP事件是不會(huì)經(jīng)過這個(gè)攔截判斷的半抱,而是直接intercepted = true表示事件被直接攔截掉脓恕。這一點(diǎn)剛好印證了我在[一步步探索學(xué)習(xí)Android Touch事件分發(fā)傳遞機(jī)制(二)](http://blog.csdn.net/alanjet/article/details/78572753)中提到的ACTION_MOVE和ACTION_UP事件的分發(fā)規(guī)律。***

- 那么mFirstTouchTarget(目標(biāo)子View)這個(gè)變量到底是什么呢窿侈?什么時(shí)候會(huì)為空呢炼幔?

- 可以看到ViewGroup的dispatchTouchEvent()方法的后續(xù)代碼,是一個(gè)for循環(huán):


    ```java
    ...
     for (int i = childrenCount - 1; i >= 0; i--) {
                                        final int childIndex = getAndVerifyPreorderedIndex(
                                                childrenCount, i, customOrder);
                                        final View child = getAndVerifyPreorderedView(
                                                preorderedList, children, childIndex);
            
                                        // If there is a view that has accessibility focus we want it
                                        // to get the event first and if not handled we will perform a
                                        // normal dispatch. We may do a double iteration but this is
                                        // safer given the timeframe.
                         
                                    }
                                    ...
    ```


    - 這個(gè)for循環(huán)一個(gè)一個(gè)的遍歷子View史简,尋找看事件的發(fā)生坐標(biāo)在哪個(gè)View的范圍中乃秀,如果找到了,就設(shè)置mFirstTouchTarget為child,并且把a(bǔ)lreadyDispatchedToNewTouchTarget設(shè)置為true圆兵。

    - 那么事件最終交給自己處理還是目標(biāo)子View(mFirstTouchTarget)處理跺讯?

    - 很簡(jiǎn)單,經(jīng)過上面的分析可以知道殉农,如果遍歷完之后mFirstTouchTarget不為null刀脏,就傳給mFirstTouchTarget(目標(biāo)子View)處理;如果為null超凳,就自己消費(fèi)掉愈污。

    - 那其實(shí)不管是給目標(biāo)子View處理還是自己處理,都會(huì)跑到View的dispatchTouchEvent()方法轮傍≡荼ⅲ看源碼可以知道,當(dāng)mFirstTouchTarget為null的時(shí)候创夜,ViewGoup會(huì)調(diào)用super.dispatchTouchEvent(event),畢竟ViewGroup本質(zhì)上是View的子類杭跪,所以其實(shí)ViewGroup調(diào)用的還是View的dispatchTouchEvent()方法。那么我們下面分析View的dispatchTouchEvent()方法挥下。

##### **1.3 View的dispatchTouchEvent()方法**

- 源碼:

    

``` java
    /**
     * 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);
        }

        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
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            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.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }
```
  • 分析:

    • 代碼量相對(duì)于ViewGroup的dispatchTouchEvnet()方法來說少很多揍魂。

    • 主要是首先判斷這個(gè)View本身有沒有設(shè)置OnTouchListener監(jiān)聽,如果有棚瘟,就直接跑去調(diào)用該接口下的onTouch()方法。該方法如果return true,這事件就是被消費(fèi)掉了喜最。return false,事件還是會(huì)傳回給onTouchEvent()方法偎蘸。

    注意:值得注意的是,ViewGroup本身并沒有重寫View的onTouchEvnet()方法,所以這里如果回傳迷雪,也是調(diào)用的父類View.java的onTouchEvent()方法限书。

2. onTouchEvent()方法源碼分析

2.1 Activity的onTouchEvent()方法
  • 源碼:
 /**
     * Called when a touch screen event was not handled by any of the views
     * under it.  This is most useful to process touch events that happen
     * outside of your window bounds, where there is no view to receive it.
     *
     * @param event The touch screen event being processed.
     *
     * @return Return true if you have consumed the event, false if you haven't.
     * The default implementation always returns false.
     */
    public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }

  • 分析:

    • 這個(gè)方法代碼很少,默認(rèn)Activity的onTouchEvent()方法是返回false的章咧,也就是說默認(rèn)不處理觸摸事件倦西。

    • 只有在PhoneWindow的shouldCloseOnTouch()方法返回true才會(huì)處理觸摸事件,直接finish整個(gè)Activity.

2.2 View的onTouchEvent()方法

前面說了赁严,ViewGroup沒有重寫View的onTouchEvent()方法扰柠,所以繼承VIewGroup時(shí),調(diào)用的還是View的onTouchEvent()疼约。

  • 源碼:
/**
     * Implement this method to handle touch screen motion events.
     * <p>
     * If this method is used to detect click actions, it is recommended that
     * the actions be performed by implementing and calling
     * {@link #performClick()}. This will ensure consistent system behavior,
     * including:
     * <ul>
     * <li>obeying click sound preferences
     * <li>dispatching OnClickListener calls
     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
     * accessibility features are enabled
     * </ul>
     *
     * @param event The motion event.
     * @return True if the event was handled, false otherwise.
     */
    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            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) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        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;
                    }
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true, x, y);
                        }

                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();
                                }
                            }
                        }

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

                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }

                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(0, x, y);
                        break;
                    }

                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(0, x, y);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    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);
                    }

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

            return true;
        }

        return false;
    }
  • 分析:

    • 代碼同樣很長(zhǎng)卤档,那么我們只去理清主要的邏輯。

    • 當(dāng)事件傳遞到該方法處程剥,首先會(huì)判斷這個(gè)View是不是enabled狀態(tài)劝枣,是不是clickable狀態(tài)。

    • 然后會(huì)根據(jù)Touch事件的類型做出不同的響應(yīng)织鲸。比如View接收到Down事件和up事件等時(shí)候的表現(xiàn)效果舔腾。

    注意:注意到一段比較重要的代碼
    if (!post(mPerformClick)) { performClick(); }
    這段代碼在判斷是up事件之后調(diào)用了performClick()方法,這個(gè)方法回去回調(diào)onClickListener接口里面的onClick()方法搂擦。
    這結(jié)合前面dispatchTouchEvent()方法中ACTION_DOWN事件會(huì)去調(diào)用onTouch稳诚,可見onTouch比onClick優(yōu)先。

3. onInterceptTouchEvent()方法源碼分析

只有ViewGroup有onInterceptTouchEvent()方法
  • 源碼:
  public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }
  • 分析:

    • 這個(gè)方法默認(rèn)是返回false盾饮,表示不攔截觸摸事件的采桃。

    • 只有在
      ev.isFromSource(InputDevice.SOURCE_MOUSE)
      && ev.getAction() == MotionEvent.ACTION_DOWN
      && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
      && isOnScrollbarThumb(ev.getX(), ev.getY())
      這么多條件同時(shí)成立時(shí)才會(huì)攔截。

  • 有需要的話丘损,比如處理滑動(dòng)沖突的時(shí)候普办,可以重寫該方法,retrun true徘钥,攔截觸摸事件衔蹲。

注:【轉(zhuǎn)載請(qǐng)注明,問題可提問呈础,喜歡可打賞舆驶,博客持續(xù)更新,歡迎關(guān)注

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末而钞,一起剝皮案震驚了整個(gè)濱河市沙廉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌臼节,老刑警劉巖撬陵,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件珊皿,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡巨税,警方通過查閱死者的電腦和手機(jī)蟋定,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來草添,“玉大人驶兜,你說我怎么就攤上這事≡洞纾” “怎么了抄淑?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)而晒。 經(jīng)常有香客問我蝇狼,道長(zhǎng),這世上最難降的妖魔是什么倡怎? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任迅耘,我火速辦了婚禮,結(jié)果婚禮上监署,老公的妹妹穿的比我還像新娘颤专。我一直安慰自己,他們只是感情好钠乏,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布栖秕。 她就那樣靜靜地躺著,像睡著了一般晓避。 火紅的嫁衣襯著肌膚如雪簇捍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天俏拱,我揣著相機(jī)與錄音暑塑,去河邊找鬼。 笑死锅必,一個(gè)胖子當(dāng)著我的面吹牛事格,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播搞隐,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼驹愚,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了劣纲?” 一聲冷哼從身側(cè)響起逢捺,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎癞季,沒想到半個(gè)月后蒸甜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體棠耕,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡余佛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年柠新,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辉巡。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡恨憎,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出郊楣,到底是詐尸還是另有隱情憔恳,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布净蚤,位于F島的核電站钥组,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏今瀑。R本人自食惡果不足惜程梦,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望橘荠。 院中可真熱鬧屿附,春花似錦、人聲如沸哥童。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贮懈。三九已至匀泊,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間朵你,已是汗流浹背各聘。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留撬呢,地道東北人伦吠。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像魂拦,于是被迫代替她去往敵國(guó)和親毛仪。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容