天天看點

Android觸屏事件處理流程淺析

在android觸屏事件中,我們經常會碰到

onclick()

,

onTouch()

,

onTouchEven()

等方法,那誰會先執行,執行順序又是怎麼樣呢?

View的觸屏事件處理

為弄清除上面那些,首先從源碼入手,看看其整個觸屏事件分發的過程.

先從

dispatchTouchEvent()

分析:

/**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

        boolean result = false;

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, );
        }

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }
        if (onFilterTouchEventForSecurity(event)) {
            //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, );
        }

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

分析這段源碼,便知道有些細節地方,如果目标View不能擷取焦點,那麼就不會處理觸屏事件,而是直接傳回false ,否則判斷目标View是否滿足注冊了

onTouchListener()

監聽以及可點選的條件,滿足則會調用

onTouch()

,如果

onTouch()

傳回true,那麼就不會再執行

onTouchEvent()

了,如果前面

onTouch()

傳回了false,那麼就會由

onTouchEvent()

的傳回值來确定最終的結果值了,是以遵從

onTouch()==true? true:onTouchEvent()

規則.在這段源碼中,可以看出其執行順序的優先級是

dispatchOnTouchEvent()

>>>>

onTouch()

>>>>

onTouchEvent()

再來看看

onTouchEvent()

在View.java源碼中有的實作:

/**
     * 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) != ) {
                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) != ;
                    if ((mPrivateFlags & PFLAG_PRESSED) !=  || 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);
                       }
                        //如果onLongClick()傳回true,就不會執行onClick()
                        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();
                    }
                    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) != ) {
                            // Remove any future long press/tap checks
                            removeLongPressCallback();

                            setPressed(false);
                        }
                    }
                    break;
            }

            return true;
        }

        return false;
    }

 private void checkForLongClick(int delayOffset) {
        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
            mHasPerformedLongPress = false;

            if (mPendingCheckForLongPress == null) {
                mPendingCheckForLongPress = new CheckForLongPress();
            }
            mPendingCheckForLongPress.rememberWindowAttachCount();
            postDelayed(mPendingCheckForLongPress,
                    ViewConfiguration.getLongPressTimeout() - delayOffset);
        }
    }

private final class CheckForTap implements Runnable {
        public float x;
        public float y;

        @Override
        public void run() {
            mPrivateFlags &= ~PFLAG_PREPRESSED;
            setPressed(true, x, y);
            checkForLongClick(ViewConfiguration.getTapTimeout());
        }
    }

private final class CheckForLongPress implements Runnable {
        private int mOriginalWindowAttachCount;

        @Override
        public void run() {
            if (isPressed() && (mParent != null)
                    && mOriginalWindowAttachCount == mWindowAttachCount) {
                    //傳回true的話,就不執行onclick()
                if (performLongClick()) {
                    mHasPerformedLongPress = true;
                }
            }
        }

        public void rememberWindowAttachCount() {
            mOriginalWindowAttachCount = mWindowAttachCount;
        }
    }

 private final class PerformClick implements Runnable {
        @Override
        public void run() {
            performClick();
        }
    }
           

這段代碼稍微多一點,但也有好多細節要注意的,如果有目标View有傳入過

TouchDelegate

對象,那麼一切來到這裡的觸屏事件都會交給其

TouchDelegate.onTouchEvent()

處理并傳回true,在

ACTION_DOWN

階段中,如果頂層容器不是滾動類的容器,那麼直接通知目标View轉變按壓視圖狀态,并且開始通過

postDelayed()

來設定

CheckForLongPress()

對象,一旦長按時間超過了

ViewConfiguration.getLongPressTimeout()

CheckForLongPress()

對象就會執行對應長按回調方法,如果頂層容器是滾動類的容器,那麼會通過

postDelayed()

傳入

CheckForTap()

對象,直到

ViewConfiguration.getTapTimeout()

時候才讓View轉變按壓視圖狀态,而不是立刻改變,同時

CheckForTap()

對象也建立對應

CheckForLongPress()

對象.同時還帶有prepressed時期标記,在

ACTION_UP

階段中,如果目标View沒有長按(既不會執行

CheckForLongPress()

對象裡的方法),同時不能擷取到焦點并傳回false,那麼便會執行

PerformClick()

對應方法,進而調用

OnClickListener.onclick()

,還有最後一點的細節就是,如果目标View滿足

CLICKABLE

,

LONG_CLICKABLE

,

CONTEXT_CLICKABLE

其中一個條件,那麼

onTouchEvent()

就會傳回true.在經過一些列的分析,可以看出其執行的順序優先級:

`onTouchEvent()

>>>>

TouchDelegate.onTouchEvent()

>>>>

onLongClick()

>>>>

onClick()

.

ViewGroup的觸屏分發實作

上面的那段是基于View.java源碼分析,那麼來分析一下其ViewGroup.java源碼,看看其又是如何分發觸屏事件的.

/**
     * 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.
     */
     //用來派發給子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) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            //如果child為空,則會回調父類的dispatchTouchEvent()
            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 == ) {
            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 {
                   //如果觸屏事件設定偏移量以和支援機關矩陣變換的子view一緻
                   //如子View做一些平移等動畫操作時的點選
                    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()) {
                //恢複原來觸屏事件發生坐标,即相當于撤銷了offsetLocation()作用
                transformedEvent.transform(child.getInverseMatrix());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }
           

在觸屏事件分發給子View的邏輯中可以知道一個細節,如果child為空,那麼會回調父類的

dispatchTouchEvent()

方法,否則就調用子View的

dispatchTouchEvent()

,執行順序的優先級:目前ViewGroup的

dispatchTouchEvent()

>>>>>childView!=null?

dispatchTouchEvent()

:

super.dispatchTouchEvent()

.

/* Describes a touched view and the ids of the pointers that it has captured.
     *
     * This code assumes that pointer ids are always in the range 0..31 such that
     * it can use a bitfield to track which pointer ids are present.
     * As it happens, the lower layers of the input dispatch pipeline also use the
     * same trick so the assumption should be safe here...
     */
    private static final class TouchTarget {
        private static final int MAX_RECYCLED = ;
        private static final Object sRecycleLock = new Object[];
        private static TouchTarget sRecycleBin;
        private static int sRecycledCount;

        public static final int ALL_POINTER_IDS = -; // all ones

        // The touched child view.
        public View child;

        // The combined bit mask of pointer ids for all pointers captured by the target.
        public int pointerIdBits;//通過位标記來記錄節點在連結清單的位置

        // The next target in the target list.
        public TouchTarget next;

        private TouchTarget() {
        }

        public static TouchTarget obtain(View child, int pointerIdBits) {
            final TouchTarget target;
            synchronized (sRecycleLock) {
                if (sRecycleBin == null) {
                    target = new TouchTarget();
                } else {
                    target = sRecycleBin;
                    sRecycleBin = target.next;
                     sRecycledCount--;
                    target.next = null;
                }
            }
            target.child = child;
            target.pointerIdBits = pointerIdBits;
            return target;
        }

        public void recycle() {
            synchronized (sRecycleLock) {
                if (sRecycledCount < MAX_RECYCLED) {
                    next = sRecycleBin;
                    sRecycleBin = this;
                    sRecycledCount += ;
                } else {
                    next = null;
                }
                child = null;
            }
        }
    }
           

通過連結清單方式來維護觸屏事件的,但在這裡有個很巧妙的地方,也通過sRecycleBin指針來複用對象,很多地方都用類似的技巧來複用對象,如listView建立item對象,具體過程如圖所示(假設初始化時,不串聯對象):

Android觸屏事件處理流程淺析

dispatchTouchEvent()

方法中,由于這段代碼還比較長,很多細節,是以我把代碼分成兩個階段去分析.

//第一階段 攔截事件時,觸屏事件的分發處理
//即某段時刻intercepted會傳回true.
 /**
     * {@inheritDoc}
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, );
        }

        // 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
                // 在ACTION_DOWN會丢棄以前的觸屏事件和清除觸屏狀态
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            //在ACTION_DOWN時候會執行或有目标子View的時候
            //如果沒有找到處理觸屏事件的View那麼其他的
            //後續觸屏事件會被目前的容器攔截,不再分發給子View
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != ;
                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) != ;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
             if (!canceled && !intercepted){
              //省略另一階段的代碼.............................   
             }                    
            // Dispatch to touch targets.
            //攔截事件且沒有子View處理觸屏事件的時候,即回調父類的dispatchTransformedTouchEvent()
            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.
                //會把在攔截事件前所捕獲到的觸屏事件交給子View去處理,攔截事件後的觸屏事件交給自己去
                處理
                TouchTarget predecessor = null;//前個觸屏事件節點
                TouchTarget target = mFirstTouchTarget;//目前觸屏事件節點
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        //派發攔截事件前的觸屏事件給子View,如果攔截(intercepted==true)
                        //則觸屏事件交給父類dispatchOnTouchEvent()
                        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 =  << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, );
        }
        return handled;
    }
           

在分析上面第一階段時,注意到一些細節處理,如果ViewGroup沒有嵌套子View的話,那麼就會回調父類的

dispatchTouchEvent()

,但如果ViewGroup有嵌套子View,但沒有一開始攔截的話,那就會将攔截前的觸屏事件交給子View

dispatchTouchEvent()

去處理,攔截後的觸屏事件交給父類的

dispatchTouchEvent()

去處理.還有一點就是如果某個子View在

dispatchTouchEvent()

onTouch()

onTouchEvent()

都不處理觸屏事件

ACTION_DOWN

ACTON_MOVE

等階段,即都傳回false,那子View就再也接受不到觸屏事件的後續階段了(如ACTION_UP).

//第二階段不攔截觸屏事件
 /**
     * {@inheritDoc}
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
            //省略代碼............................................
            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 ?  << 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 != ) {
                        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 = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - ; i >= ; i--) {
                            final int childIndex = customOrder
                                    ? getChildDrawingOrder(childrenCount, i) : i;
                            final View child = (preorderedList == null)
                                    ? children[childIndex] : preorderedList.get(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 - ;
                            }

                            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 = ; 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;
                    }
                }
            }
        //省略代碼.........................................................
        return handled;
    }
           

這段代碼主要處理

ACTION_DOWN

階段,隻在

ACTION_DOWN

階段僅一次或0次調用

onInterceptTouchEvent()

來決定要不要攔截觸屏事件,如果不攔截,那就找消費觸屏事件的子View,即子View處理觸屏事件的最終結果傳回true,然後做一些記錄操,最後用連結清單串聯觸屏對象.在結合第一段階段的代碼,可以看出其觸屏事件執行順序的優先級:

目前容器的dispatchTouchEvent()

>>>>>

onInterceptTouchEvent()

>>>>>

childView!=null?dispatchTouchEvent():super.dispatchTouchEvent()

.

觸屏事件處理DEMO

上面圍繞一大堆源碼分析後,可能很容易被搞混,為印象更加深刻,基于上面理論實踐一個demo來驗證,并畫出對應的處理流程圖.

public class MyButton extends Button implements View.OnClickListener,View.OnTouchListener,View.OnLongClickListener{

    private static final String TAG = MyButton.class.getName();

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
        setOnTouchListener(this);
        setOnLongClickListener(this);
        Button button=new Button(context){
            @Override
            public boolean onTouchEvent(MotionEvent event) {
                Log.i(TAG,"OtherButton>>>>>>>>>>>onTouchEvent()");
                return true;
            }
        };
        DisplayMetrics displayMetrics=context.getResources().getDisplayMetrics();
        setTouchDelegate(new TouchDelegate(new Rect(,,displayMetrics.widthPixels,displayMetrics.heightPixels),button));
    }

    @Override
    public boolean onLongClick(View view) {
        Log.i(TAG,"MyButton>>>>>>>>>>>onLongClick");
        return false;
    }


    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        Log.i(TAG,"MyButton>>>>>>>>>>>onTouch");
        return false;
    }

    @Override
    public void onClick(View view) {
        Log.i(TAG,"MyButton>>>>>>>>>>>onClick");

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i(TAG,"MyButton>>>>>>>>>>>onTouchEvent");
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        Log.i(TAG,"event_action>>>>>>>>>>>"+event.getAction());
        Log.i(TAG,"MyButton>>>>>>>>>>>DispatchTouchEvent");
        return super.dispatchTouchEvent(event);
    }
}
           
Android觸屏事件處理流程淺析

将代理的button的

onTouch()

傳回false.其短按和長按事件處理流程如圖:

短按:

Android觸屏事件處理流程淺析

長按:

Android觸屏事件處理流程淺析

對于View處理觸屏事件的其他的情況,我就不再一一測試了,總的來說,View處理觸屏事件流程就如圖所示:

Android觸屏事件處理流程淺析
//子布局
public class MyButton extends Button implements View.OnClickListener, View.OnTouchListener, View.OnLongClickListener {

  private static final String TAG = MyButton.class.getName();

  public MyButton(Context context, AttributeSet attrs) {
    super(context, attrs);    
  }
  @Override
  public boolean dispatchTouchEvent(MotionEvent event) {
    switch (event.getAction()){
      case MotionEvent.ACTION_DOWN:
        Log.i(TAG, "ACTION_DOWN>>>>>>>>>>>DispatchTouchEvent");
        break;
      case MotionEvent.ACTION_MOVE:
        Log.i(TAG, "ACTION_MOVE>>>>>>>>>>>DispatchTouchEvent");
        break;
      case MotionEvent.ACTION_UP:
        Log.i(TAG, "ACTION_UP>>>>>>>>>>>DispatchTouchEvent");
        break;
    }
    return false;
  }

}

//父布局,該布局會嵌套MyButton
public class MyRelativeLayout extends RelativeLayout {

  private static final String TAG = MyRelativeLayout.class.getName();

  public MyRelativeLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    //setClickable(true);
  }

  @Override
  public boolean dispatchTouchEvent(MotionEvent event) {
    switch (event.getAction()){
      case MotionEvent.ACTION_DOWN:
        Log.i(TAG, "ACTION_DOWN>>>>>>>>>>>dispatchTouchEvent");
        break;
      case MotionEvent.ACTION_MOVE:
        Log.i(TAG, "ACTION_MOVE>>>>>>>>>>>dispatchTouchEvent");
        break;
      case MotionEvent.ACTION_UP:
        Log.i(TAG, "ACTION_UP>>>>>>>>>>>dispatchTouchEvent");
        break;
    }
    return super.dispatchTouchEvent(event);
  }

  @Override
  public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch (ev.getAction()){
      case MotionEvent.ACTION_DOWN:
        Log.i(TAG, "ACTION_DOWN>>>>>>>>>>>onInterceptTouchEvent");
        break;
      case MotionEvent.ACTION_MOVE:
        Log.i(TAG, "ACTION_MOVE>>>>>>>>>>>onInterceptTouchEvent");
        break;
      case MotionEvent.ACTION_UP:
        Log.i(TAG, "ACTION_UP>>>>>>>>>>>onInterceptTouchEvent");
        break;
    }
    return false;
  }

  @Override
  public String toString() {
    return "MyRelativeLayout";
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()){
      case MotionEvent.ACTION_DOWN:
        Log.i(TAG, "ACTION_DOWN>>>>>>>>>>>onTouchEvent");
        break;
      case MotionEvent.ACTION_MOVE:
        Log.i(TAG, "ACTION_MOVE>>>>>>>>>>>onTouchEvent");
        break;
      case MotionEvent.ACTION_UP:
        Log.i(TAG, "ACTION_UP>>>>>>>>>>>onTouchEvent");
        break;
    }
    return true;
  }
}
           
Android觸屏事件處理流程淺析

日志可以看出子View沒有消費觸屏事件的話,會回傳給父容器去處理觸屏事件的,并且隻在ACTION_DOWN階段調用

onInterceptTouchEvent()

,再把

MyRelativeLayout.onInterceptTouchEvent()

改為true.

Android觸屏事件處理流程淺析

再把

MyRelativeLayout.onTouchEvent()

傳回false,那麼又會怎麼樣呢?

public class MainActivity extends AppCompatActivity {

  private static final String TAG = MainActivity.class.getName();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
    switch (ev.getAction()){
      case MotionEvent.ACTION_DOWN:
        Log.i(TAG, "ACTION_DOWN>>>>>>>>>>>dispatchTouchEvent");
        break;
      case MotionEvent.ACTION_MOVE:
        Log.i(TAG, "ACTION_MOVE>>>>>>>>>>>dispatchTouchEvent");
        break;
      case MotionEvent.ACTION_UP:
        Log.i(TAG, "ACTION_UP>>>>>>>>>>>dispatchTouchEvent");
        break;
    }
    return super.dispatchTouchEvent(ev);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()){
      case MotionEvent.ACTION_DOWN:
        Log.i(TAG, "ACTION_DOWN>>>>>>>>>>>onTouchEvent");
        break;
      case MotionEvent.ACTION_MOVE:
        Log.i(TAG, "ACTION_MOVE>>>>>>>>>>>onTouchEvent");
        break;
      case MotionEvent.ACTION_UP:
        Log.i(TAG, "ACTION_UP>>>>>>>>>>>onTouchEvent");
        break;
    }
    return true;
  }
}
           
Android觸屏事件處理流程淺析

子View再也沒有收到觸屏事件了吧,如果最頂層容器

onTouchEvent()

傳回false不消費觸屏事件的話,那麼回回傳給Actvitiy的

onTouchEvent()

去處理,即使Activitiy的

onTouchEvent()

傳回false,也會能接受到觸屏事件的後續階段.到這裡,我畫個總的流程圖來概況一下:

Android觸屏事件處理流程淺析