Android View從源碼的角度分析Touch事件傳遞流程

都知道在Android中的事件主要包括三部分內(nèi)容:分發(fā)事件dispatchTouchEvent、攔截事件onInterceptTouchEvent、消費事件onTouchEvent。這幾乎是所有開發(fā)者都要面臨的問題,無論是解決一些事件沖突問題,還是自定義View,都會或多或少涉及到。由于其獨特的重要性,大多數(shù)面試的時候也基本會有所涉及,所以很好的掌握View的Touch事件傳遞顯得尤其重要。

1、Activity的dispatchTouchEvent

首先來看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) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

如果事件為按下狀態(tài),則先調(diào)用onUserInteraction方法:

      /**
     * Called whenever a key, touch, or trackball event is dispatched to the
     * activity.  Implement this method if you wish to know that the user has
     * interacted with the device in some way while your activity is running.
     * This callback and {@link #onUserLeaveHint} are intended to help
     * activities manage status bar notifications intelligently; specifically,
     * for helping activities determine the proper time to cancel a notfication.
     *
     * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
     * be accompanied by calls to {@link #onUserInteraction}.  This
     * ensures that your activity will be told of relevant user activity such
     * as pulling down the notification pane and touching an item there.
     *
     * <p>Note that this callback will be invoked for the touch down action
     * that begins a touch gesture, but may not be invoked for the touch-moved
     * and touch-up actions that follow.
     *
     * @see #onUserLeaveHint()
     */
    public void onUserInteraction() {
    }

該方法為空,從注釋可以知道,當(dāng)此activity在棧頂時,觸屏點擊按home、back、menu鍵等都會觸發(fā)此方法,一般會用于屏保。

接著調(diào)用了getWindow().superDispatchTouchEvent(ev),即PhoneWindow類(Window的具體實現(xiàn)類)的superDispatchTouchEvent方法:

      @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

簡單調(diào)用了mDecor.superDispatchTouchEvent(event),即DecorView的superDispatchTouchEvent方法:

      public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

我們知道DecorView繼承自FrameLayout,F(xiàn)rameLayout又繼承了ViewGroup,所以這里就是調(diào)用了ViewGroup的dispatchTouchEvent方法。

所以執(zhí)行g(shù)etWindow().superDispatchTouchEvent(ev)實際上是執(zhí)行了ViewGroup.dispatchTouchEvent(event),這樣事件就從 Activity 傳遞到了 ViewGroup。這里后續(xù)會接著分析。

這里需要注意的是:

當(dāng)getWindow().superDispatchTouchEvent(ev)返回true時,即Activity的子View攔截了TouchEvent事件,那么接下來就不會再傳遞給Activity的onTouchEvent 方法,同時Activity的dispatchTouchEvent方法返回true;

反之返回false時,這個事件就交給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;
    }

可以看到Activity的onTouchEvent 方法返回了false,也就意味著當(dāng)getWindow().superDispatchTouchEvent(ev)返回false時,Activity的dispatchTouchEvent方法默認返回false。

2、ViewGroup的dispatchTouchEvent

如果要很好掌握Touch事件處理,這部分要重點學(xué)習(xí),而且不同Android版本的實現(xiàn)不一致,本文仍然使用最新的Android 7.1源碼,相比之前的源碼加入了更多的復(fù)雜邏輯操作,但是最基本的流程保持一致。

接下來直接分析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();
            }
            ...
        }
        ...
    }

其中第一個if語句主要用于調(diào)試可直接忽略,后面的變量handled用于表示是否有view消費了該事件,接著調(diào)用了父類View的onFilterTouchEventForSecurity方法來判斷是否被其他窗口遮蓋,方法具體如下:

     /**
     * Filter the touch event to apply security policies.
     *
     * @param event The motion event to be filtered.
     * @return True if the event should be dispatched, false if the event should be dropped.
     *
     * @see #getFilterTouchesWhenObscured
     */
    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
        //noinspection RedundantIfStatement
        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
            // Window is obscured, drop this touch.
            return false;
        }
        return true;
    }

如果被其他窗口遮擋,該方法返回false,表示需要過濾觸摸事件,就會跳過dispatchTouchEvent方法中的if語句代碼,直接退出dispatchTouchEvent方法并返回false,表示沒有View消費Touch事件;如果沒有被其他窗口遮擋,該方法返回true,進而繼續(xù)執(zhí)行if語句里面的代碼。

每一個事件都是由一個觸摸按下事件,一個觸摸抬起事件和N個觸摸滑動事件組成的,觸摸按下事件就是這里的ACTION_DOWN,其為一系列事件的開端。所以在ACTION_DOWN時進行一些初始化操作,分別調(diào)用了cancelAndClearTouchTargets方法和resetTouchState方法,用來清楚掉之前消費Touch事件的View信息,并重置觸摸狀態(tài)。

首先來看cancelAndClearTouchTargets方法:

    /**
     * Cancels and clears all touch targets.
     */
    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);
            }
            clearTouchTargets();
 
            if (syntheticEvent) {
                event.recycle();
            }
        }
    }

首先判斷目標View,如果存在則進行統(tǒng)一清除操作。如果event為空,則將動作設(shè)為ACTION_CANCEL,接著用一個for循環(huán)不斷向下傳遞觸摸事件,然后再清除所有觸摸目標,最后在回收拷貝的對象。

接著再來看resetTouchState方法:

    /**
     * Resets all touch state in preparation for a new cycle.
     */
    private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }

該方法非常簡單,就是重置了一些Touch標志位。

然后繼續(xù)回到dispatchTouchEvent方法,看第二個代碼塊:

            // 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;

變量intercepted用來標記是否要攔截該Touch事件,true表示攔截,false表示不攔截。

接著一個if判斷語句,如果為ACTION_DOWN事件,此時還沒有找到消費Touch事件的View,所以mFirstTouchTarget為空;如果為ACTION_MOVE和ACTION_UP事件,當(dāng)前面的ACTION_DOWN事件找到了消費Touch事件的View則mFirstTouchTarget不為空。這兩種情況都可以執(zhí)行if里面的代碼塊。

變量disallowIntercept 用來標記是否允許攔截,默認為false,但是可以通過 requestDisallowInterceptTouchEvent方法來重置該變量的值。

如果允許攔截,則調(diào)用onInterceptTouchEvent方法,即我們熟知的攔截事件。該方法代碼如下:

     /**
     * Implement this method to intercept all touch screen motion events.  This
     * allows you to watch events as they are dispatched to your children, and
     * take ownership of the current gesture at any point.
     *
     * <p>Using this function takes some care, as it has a fairly complicated
     * interaction with {@link View#onTouchEvent(MotionEvent)
     * View.onTouchEvent(MotionEvent)}, and using it requires implementing
     * that method as well as this one in the correct way.  Events will be
     * received in the following order:
     *
     * <ol>
     * <li> You will receive the down event here.
     * <li> The down event will be handled either by a child of this view
     * group, or given to your own onTouchEvent() method to handle; this means
     * you should implement onTouchEvent() to return true, so you will
     * continue to see the rest of the gesture (instead of looking for
     * a parent view to handle it).  Also, by returning true from
     * onTouchEvent(), you will not receive any following
     * events in onInterceptTouchEvent() and all touch processing must
     * happen in onTouchEvent() like normal.
     * <li> For as long as you return false from this function, each following
     * event (up to and including the final up) will be delivered first here
     * and then to the target's onTouchEvent().
     * <li> If you return true from here, you will not receive any
     * following events: the target view will receive the same event but
     * with the action {@link MotionEvent#ACTION_CANCEL}, and all further
     * events will be delivered to your onTouchEvent() method and no longer
     * appear here.
     * </ol>
     *
     * @param ev The motion event being dispatched down the hierarchy.
     * @return Return true to steal motion events from the children and have
     * them dispatched to this ViewGroup through onTouchEvent().
     * The current target will receive an ACTION_CANCEL event, and no further
     * messages will be delivered here.
     */
    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;
    }

該方法是ViewGroup中特有的方法,用于表示是否攔截觸摸事件。返回為true的話則表示攔截事件,事件不在向子View中分發(fā),若返回false的話,則表示不攔截事件,將繼續(xù)分發(fā)事件。

正常都是返回默認的false,但是一般我們在自定義ViewGroup中會重寫該方法,用于攔截事件的分發(fā)。當(dāng)我們在父ViewGroup重寫該方法返回為true執(zhí)行事件攔截的邏輯的時候,可以在子View中通過調(diào)用requestDisallowInterceptTouchEvent方法,重新設(shè)置父ViewGroup的onInterceptTouchEvent方法為false,不攔截對事件的分發(fā)邏輯。

這里也是我們在開發(fā)中接觸碰到的問題,所以需要好好理解一下,下面為requestDisallowInterceptTouchEvent方法的源碼:

    @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);
        }
    }

攔截事件判斷完成后,會接著調(diào)用resetCancelNextUpFlag方法來檢查當(dāng)前事件是否被取消。

    /**
     * Resets the cancel next up flag.
     * Returns true if the flag was previously set.
     */
    private static boolean resetCancelNextUpFlag(@NonNull View view) {
        if ((view.mPrivateFlags & PFLAG_CANCEL_NEXT_UP_EVENT) != 0) {
            view.mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
            return true;
        }
        return false;
    }

繼續(xù)回到dispatchTouchEvent方法,看第三個代碼塊:

             // 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;
                    }
                }
            }

該段代碼首先是一個if判斷語句,如果事件沒有被取消,也沒有被攔截,就分發(fā)該事件。只有ACTION_DOWN事件才會執(zhí)行第二個if語句里面的代碼,對于ACTION_MOVE和ACTION_UP事件則直接傳給消費了ACTION_DOWN事件的目標View。

接著獲取該ViewGroup中子View的個數(shù),得到該事件發(fā)生的位置,獲取子View的list集合preorderedList,再通過for循環(huán)倒序遍歷當(dāng)前ViewGroup的所有子視圖。

有一點值得注意的是,這里采用了倒序遍歷,這是由于preorderedList中的順序是按照addView或XML布局文件中的順序來的。如點擊的地方有兩個子View都包含點擊事件的坐標,那么后被添加到布局中的那個子view會先響應(yīng)事件,即點擊的時候最上層的那個組件先去響應(yīng)該事件。

在for循環(huán)中第一個if語句調(diào)用了canViewReceivePointerEvents(child)和isTransformedTouchPointInView(x, y, child, null)方法。

    /**
     * Returns true if a child view can receive pointer events.
     * @hide
     */
    private static boolean canViewReceivePointerEvents(@NonNull View child) {
        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                || child.getAnimation() != null;
    }

該方法用于判斷當(dāng)前視圖的狀態(tài),只有其正在顯示或正在執(zhí)行動畫,才可以接受觸摸事件。

    /**
     * Returns true if a child view contains the specified point when transformed
     * into its coordinate space.
     * Child must not be null.
     * @hide
     */
    protected boolean isTransformedTouchPointInView(float x, float y, View child,
            PointF outLocalPoint) {
        final float[] point = getTempPoint();
        point[0] = x;
        point[1] = y;
        transformPointToViewLocal(point, child);
        final boolean isInView = child.pointInView(point[0], point[1]);
        if (isInView && outLocalPoint != null) {
            outLocalPoint.set(point[0], point[1]);
        }
        return isInView;
    }

判斷視圖有scrollTo或scrollBy造成的滾動偏移也需要計算在內(nèi),并判斷觸摸點是否在當(dāng)前子視圖內(nèi)。

從這兩個方法可知,如果當(dāng)前子View可以消費該ACTION_DOWN事件,并且該ACTION_DOWN事件發(fā)生的位置在當(dāng)前子View的范圍內(nèi),則繼續(xù)執(zhí)行將ACTION_DOWN事件分發(fā)給它;否則continue判斷下一個子View可否接受該ACTION_DOWN事件。

然后代碼通過調(diào)用getTouchTarget方法去查找當(dāng)前子View是否在mFirstTouchTarget.next這條target鏈中的某一個targe中,如果在則返回這個target,否則返回null。緊接著用if判斷找到接收Touch事件的子View,即newTouchTarget,既然已經(jīng)找到則執(zhí)行break跳出for循環(huán)。

如果該子View還沒有消費掉該ACTION_DOWN事件,就直接調(diào)用dispatchTransformedTouchEvent方法將該ACTION_DOWN事件傳遞給該子View。

    /**
     * Transforms a motion event into the coordinate space of a particular child view,
     * filters out irrelevant pointer ids, and overrides its action if necessary.
     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
     */
    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) {
            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;
        }
 
        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
        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) {
            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());
            }
 
            handled = child.dispatchTouchEvent(transformedEvent);
        }
 
        // Done.
        transformedEvent.recycle();
        return handled;
    }

該方法是一個非常重要的方法,其主要包括三塊內(nèi)容,結(jié)構(gòu)雷同。而且會發(fā)現(xiàn)該方法中代碼為一個遞歸調(diào)用,若其子View是ViewGroup則重復(fù)執(zhí)行ViewGroup的dispatchTouchEvent方法,若其子View是View則執(zhí)行View的dispatchTouchEvent方法。

從最開始到這里,我們大概分析了一下事件分發(fā)流程,通過調(diào)用Activity的dispatchTouchEvent方法,事件會首先被派發(fā)到最頂級的DecorView也就是ViewGroup,再由ViewGroup遞歸傳遞到View的dispatchTouchEvent方法。對于View的dispatchTouchEvent方法,我們后面再做分析。

如果dispatchTransformedTouchEvent方法返回true,則表示子View消費掉該事件。那么就回到dispatchTouchEvent方法繼續(xù)執(zhí)行if語句里的代碼塊,將子View加入到mFirstTouchTarget鏈表的表頭,并且將該表頭賦值給newTouchTarget,同時 alreadyDispatchedToNewTouchTarget置為true,說明有子View消費掉了該down事件。

for循環(huán)執(zhí)行完畢后,如果newTouchTarget為null,且 mFirstTouchTarget不為null,即沒找到子View來消耗該事件,但為了保存Touch事件的鏈表不為空,則把newTouchTarget賦值為最早加進mFirstTouchTarget鏈表的target。

再看dispatchTouchEvent方法的第四個代碼塊:

             // 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;
                }
            }

如果沒有找到消費Touch事件的子View,則直接把當(dāng)前的ViewGroup當(dāng)作普通的View看待,把事件傳遞給自己,即前面分析的dispatchTransformedTouchEvent方法中child為null的情況;如果之前的ACTION_DOWN事件被子View消費掉了,就會直接找到該子View對應(yīng)的Target,將ACTION_MOVE和ACTION_UP事件傳遞給它們。

這里需要注意的是,如果intercepted為true,也就是ACTION_MOVE和ACTION_UP事件被攔截了,則cancelChild為true,則會分發(fā)一次ACTION_CANCLE事件。

再看dispatchTouchEvent方法的第五個代碼塊:

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        ...
        if (onFilterTouchEventForSecurity(ev)) {
            ...
            // 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;
    }

如果當(dāng)前事件是ACTION_CANCLE或ACTION_UP,會調(diào)用resetTouchState方法清空Touch狀態(tài)。

至此,ViewGroup的dispatchTouchEvent方法分析完畢。

3、View的dispatchTouchEvent

在分析ViewGroup的dispatchTouchEvent方法時,里面多處調(diào)用了dispatchTransformedTouchEvent方法,最終將事件從ViewGroup傳遞到 View,那么事件在后續(xù)如何傳遞的,接下來繼續(xù)分析。

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

相比較ViewGroup的dispatchTouchEvent方法,View的dispatchTouchEvent方法要簡便得多。當(dāng)View沒有被其他窗口遮擋時,判斷mOnTouchListener是否為空,即判斷該View有沒有綁定OnTouchListener監(jiān)聽器。

從源碼里面可以找到,mOnTouchListener是通過setOnTouchListener方法來進行綁定的:

      /**
     * Register a callback to be invoked when a touch event is sent to this view.
     * @param l the touch listener to attach to this view
     */
    public void setOnTouchListener(OnTouchListener l) {
        getListenerInfo().mOnTouchListener = l;
    }

OnTouchListener監(jiān)聽器如下:

    /**
     * Interface definition for a callback to be invoked when a touch event is
     * dispatched to this view. The callback will be invoked before the touch
     * event is given to the view.
     */
    public interface OnTouchListener {
        /**
         * Called when a touch event is dispatched to a view. This allows listeners to
         * get a chance to respond before the target view.
         *
         * @param v The view the touch event has been dispatched to.
         * @param event The MotionEvent object containing full information about
         *        the event.
         * @return True if the listener has consumed the event, false otherwise.
         */
        boolean onTouch(View v, MotionEvent event);
    }

當(dāng)前View一旦執(zhí)行了setOnTouchListener方法,該View的mOnTouchListener就不為空,就會調(diào)用OnTouchListener監(jiān)聽器的OnTouch方法。從返回值可以看到,如果重寫的OnTouch方法返回true的話,那么result的值就為true,意味著該事件被消費掉了,就不會繼續(xù)執(zhí)行后面的onTouchEvent方法了;否則繼續(xù)執(zhí)行onTouchEvent方法。

4、View的onTouchEvent

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();
 
        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return (((viewFlags & CLICKABLE) == CLICKABLE
                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
 
        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    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:
                    mHasPerformedLongPress = false;
 
                    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:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    break;
 
                case MotionEvent.ACTION_MOVE:
                    drawableHotspotChanged(x, y);
 
                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        removeTapCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            // Remove any future long press/tap checks
                            removeLongPressCallback();
 
                            setPressed(false);
                        }
                    }
                    break;
            }
 
            return true;
        }
 
        return false;
    }

該方法代碼比較多,但是思路非常清晰。可以從第一個if語句看到,即使View為 disable 狀態(tài),其依然可以消耗事件。從后面的if語句可以看到,當(dāng) View 的 LongClick 或 Clickable 屬性,只要有一個為 true則能消耗事件,執(zhí)行onClick和onLongClick方法。

其中onClick是在ACTION_UP事件中執(zhí)行的,onLongClick是在ACTION_DOWN事件中執(zhí)行的,分別對應(yīng)performClick和checkForLongClick方法。

    /**
     * Call this view's OnClickListener, if it is defined.  Performs all normal
     * actions associated with clicking: reporting accessibility event, playing
     * a sound, etc.
     *
     * @return True there was an assigned OnClickListener that was called, false
     *         otherwise is returned.
     */
    public boolean performClick() {
        final boolean result;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }
 
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
        return result;
    }

上面代碼判斷mOnClickListener是否為空,即判斷該View有沒有綁定OnClickListener監(jiān)聽器。如果通過調(diào)用setOnClickListener方法綁定了OnClickListener監(jiān)聽器,則調(diào)用onClick方法。

    /**
     * Register a callback to be invoked when this view is clicked. If this view is not
     * clickable, it becomes clickable.
     *
     * @param l The callback that will run
     *
     * @see #setClickable(boolean)
     */
    public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

接著來看checkForLongClick方法的源碼:

    private void checkForLongClick(int delayOffset, float x, float y) {
        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
            mHasPerformedLongPress = false;
 
            if (mPendingCheckForLongPress == null) {
                mPendingCheckForLongPress = new CheckForLongPress();
            }
            mPendingCheckForLongPress.setAnchor(x, y);
            mPendingCheckForLongPress.rememberWindowAttachCount();
            postDelayed(mPendingCheckForLongPress,
                    ViewConfiguration.getLongPressTimeout() - delayOffset);
        }
    }

由于長按事件比較復(fù)雜,需要根據(jù)ACTION_DOWN事件開始計時,所以這里新建了一個CheckForLongPress對象,其實際為一個Runnable對象:

    private final class CheckForLongPress implements Runnable {
        private int mOriginalWindowAttachCount;
        private float mX;
        private float mY;
 
        @Override
        public void run() {
            if (isPressed() && (mParent != null)
                    && mOriginalWindowAttachCount == mWindowAttachCount) {
                if (performLongClick(mX, mY)) {
                    mHasPerformedLongPress = true;
                }
            }
        }
 
        public void setAnchor(float x, float y) {
            mX = x;
            mY = y;
        }
 
        public void rememberWindowAttachCount() {
            mOriginalWindowAttachCount = mWindowAttachCount;
        }
    }

run方法中調(diào)用了performLongClick 方法,繼續(xù)追蹤:

    /**
     * Calls this view's OnLongClickListener, if it is defined. Invokes the
     * context menu if the OnLongClickListener did not consume the event,
     * anchoring it to an (x,y) coordinate.
     *
     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
     *          to disable anchoring
     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
     *          to disable anchoring
     * @return {@code true} if one of the above receivers consumed the event,
     *         {@code false} otherwise
     */
    public boolean performLongClick(float x, float y) {
        mLongClickX = x;
        mLongClickY = y;
        final boolean handled = performLongClick();
        mLongClickX = Float.NaN;
        mLongClickY = Float.NaN;
        return handled;
    }

繼續(xù)調(diào)用了重載的performLongClick 方法:

    /**
     * Calls this view's OnLongClickListener, if it is defined. Invokes the
     * context menu if the OnLongClickListener did not consume the event.
     *
     * @return {@code true} if one of the above receivers consumed the event,
     *         {@code false} otherwise
     */
    public boolean performLongClick() {
        return performLongClickInternal(mLongClickX, mLongClickY);
    }

直接調(diào)用了performLongClickInternal方法:

    /**
     * Calls this view's OnLongClickListener, if it is defined. Invokes the
     * context menu if the OnLongClickListener did not consume the event,
     * optionally anchoring it to an (x,y) coordinate.
     *
     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
     *          to disable anchoring
     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
     *          to disable anchoring
     * @return {@code true} if one of the above receivers consumed the event,
     *         {@code false} otherwise
     */
    private boolean performLongClickInternal(float x, float y) {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
 
        boolean handled = false;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnLongClickListener != null) {
            handled = li.mOnLongClickListener.onLongClick(View.this);
        }
        if (!handled) {
            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
        }
        if (handled) {
            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
        return handled;
    }

上面代碼判斷mOnLongClickListener是否為空,即判斷該View有沒有綁定OnLongClickListener監(jiān)聽器。如果通過調(diào)用setOnLongClickListener方法綁定了OnLongClickListener監(jiān)聽器,則調(diào)用onLongClick方法。

    /**
     * Register a callback to be invoked when this view is clicked and held. If this view is not
     * long clickable, it becomes long clickable.
     *
     * @param l The callback that will run
     *
     * @see #setLongClickable(boolean)
     */
    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
        if (!isLongClickable()) {
            setLongClickable(true);
        }
        getListenerInfo().mOnLongClickListener = l;
    }

從以上的代碼分析知道,如果在ACTION_DOWN事件中已經(jīng)執(zhí)行了onLongClick的話,則mHasPerformedLongPress變量會被置為true,這樣在ACTION_UP事件中,就會把onClick的回調(diào)remove掉,就不會再執(zhí)行onClick了。

至此,Touch事件的傳遞流程分析完畢。

總結(jié)

按照上面一步一步分析,流程確實比較復(fù)雜,只是便于理解具體如何傳遞的,最后再把其中的關(guān)鍵流程總結(jié)一下。主要有以下幾點:

image

事件從Activity.dispatchTouchEveent()開始傳遞,只要沒有攔截,就會從最上層(ViewGroup)開始一直往下傳遞,子View通過onTouchEvent()消費事件。如果事件從上往下一直傳遞到最底層的子View,但是該View并沒有消費該事件,那么該事件就會反序往上傳遞,即從該View傳遞給自己的ViewGroup,然后再傳給更上層的ViewGroup直至傳遞給Activity.onTouchEvent()。

事件從ViewGroup傳遞給子View時,其中ViewGroup可以通過onInterceptTouchEvent()方法對事件進行攔截,停止其往下傳遞,如果攔截(即返回true)后該事件會直接走到該ViewGroup中的onTouchEvent()方法,不會再往下傳遞給子View。如果從DOWN開始,之后的MOVE、UP都會直接在該ViewGroup.onTouchEvent()中進行處理。

image

如果子View之前在處理某個事件,但是后續(xù)被ViewGroup攔截,那么子View會接收到ACTION_CANCEL。如果View沒有消費ACTION_DOWN事件,之后其他的ACTION_MOVE和ACTION_UP等事件都不會傳遞過來。

OnTouchListener優(yōu)先于onTouchEvent()對事件進行消費,onLongClick優(yōu)先于oClick對事件進行消費。

image

這一塊的內(nèi)容詳細分析確實比較麻煩,但是整體疏通以后看起來大體還算比較簡單的。如果有疑問,歡迎留言一起相互探討共同進步。

原文鏈接:手把手教你讀懂源碼,View的Touch事件傳遞流程詳細剖析

View系列文章:
Android View從源碼的角度分析加載流程
Android View從源碼的角度分析繪制流程
Android View從源碼的角度分析事件的注冊和接收

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

相關(guān)閱讀更多精彩內(nèi)容

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