藝術開發(fā)-事件分發(fā)

(1)同一個事件序列是從手指接觸屏幕的那一刻開始的,到手指離開屏幕的那一刻結束.這個事件序列從Down事件開始中間含有數(shù)量不定的Move事件,最終以Up事件結束
(2) 正常情況下,一個時間序列只能被一個View攔截且消耗,因為一旦一個元素攔截了某個事件,那么同一個時間序列內的所有事件都會直接交給他處理,因此同一個事件序列內的事件不能分別有兩個View同時處理,但是通過其他手段,比如把一個View的本該自己處理的事件通過onTouchEvent強行傳遞給其他View處理
(3)某個view如果決定攔截,那么這個事件序列都只能由他來處理(前提是這個事件序列能夠傳遞給他),并且他的onInterceptTouchEvent(ev)不會被調用

(2)(3)解釋:

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

  • 上面一段代碼是從ViewGroup中的dispatchTouchEvent()方法中得到的,Down事件容易理解, mFirstTouchTarget != null解釋一下,當事件由ViewGroup的子元素成功處理時 mFirstTouchTarget 會被賦值并指向子元素,就是說,如果是ViewGroup消費了事件,那么他的Down事件到來的時候肯定會調用onInterceptTouchEvent(ev)方法,判斷是否攔截,當后續(xù)的Up和Move事件到來的時候因為mFirstTouchTarget != null為false,所以onInterceptTouchEvent(ev)就不會調用了.

  • 如果ViewGroup沒有消費事件而是子元素消費了事件,那么mFirstTouchTarget != null就為true了,因為final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;默認為false表示不攔截事件,所以onInterceptTouchEvent(ev);將會被會被調用

(4)某個View一旦開始處理事件,如果他不消耗Down事件(也就是說他的onTouchEvent返回了false),那么同一事件中的其他事件都不會交給他來處理.并且事件將重新交給他的父元素處理,也就是說這個時候他的父元素的onTouchEvent將會被調用.通俗一點說就是事件一旦交給一個View處理,那么他就必須消耗掉,否則同一事件序列中剩下的其他事件就不再交給他來處理。

(4)解釋:

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;
                            }
  • 這個事ViewGroup中的dispatchTouchEvent()方法中的一段代碼,其中dispatchTransformedTouchEvent()方法內部就是調用子元素的dispatchTransformedTouchEvent();方法,如果子元素在Down事件中沒有消費,就會返回false,因為這個方法是在for循環(huán)中進行的,就會遍歷下面的view,如果返回的是true,就會跳出循環(huán)

(5)如果View不消耗除Down事件以外的其他事件,那么這個點擊事件會消失,此時父元素的onTouchEvent不會被調用,并且當前View可以持續(xù)收到后續(xù)的事件,最終這些消失的點擊事件都會傳遞給Activity處理
(6)ViewGroup默認不攔截任何事件.android源碼中的ViewGroup的onInterceptTouchEvent(ev)默認返回false
(7)View沒有onInterceptTouchEvent(ev)方法, 一旦有點擊事件傳遞給他,那么他的onTuchEvent方法就會被調用
(8)View的onTouchEvent默認都會消耗事件(也就是說返回true),除非他是不可點擊的(也就是說他的aclickable和longClickable同時為false).View的longClickable屬性默認都為false,clickable屬性要分情況,比如Button的clickable屬性默認為true,而TextView的clickable屬性默認為false.
(9)View的enable屬性不影響onTouchEvent的默認返回值.哪怕iew是disable狀態(tài)
(10)onClick會發(fā)生的前提是當前View是可點擊的,并且他收到了down和up事件
(11)事件的傳遞過程是有外向內的,即事件總是先傳給父元素,然后在由父元素分發(fā)給子View,通過 requestDisallowInterceptTouchEvent()可以在子元素中干預父元素的分發(fā)過程,但是Down事件除外,因為父元素在Down事件來的時候會初始化requestDisallowInterceptTouchEvent()這個方法的東西,和面會解釋

(8)(9)(10)解釋:

 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);
                    }
                    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;
    }
</pre>
上面的是View的onTouchEvent方法,里面內容比較多我們單抽出來講
<pre>
 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) {
                       ......
                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            removeLongPressCallback();
                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {                          
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();
                                }
                            }
                        } 
                    }
                    break;
            }
            return true;
        }
        return false;
    }
  • 上面是精簡版的View的onTouchEvent方法,我們把一些英文注釋刪了,反正也看不懂,還有Down Move Cancel三個事件刪了,因為這個幾個事件對整個分發(fā)沒有起到任何影響,同時還影響我們代碼的可讀性.從上面的代碼中我們看到上面藍色的部分是一個if包裹的,如果滿足了這個if條件就會返回true,從上面的代碼中可以看到只要View的Clickable和longClickable有一個為true,那他就會消耗這個事件,也就是說onTouchEvent方法返回true.這里面還有一個很重要的方法就是performClick()方法,當Up事件發(fā)生時,就會調用這個方法,其實他內部調用的就是我們的額onClick方法,前提是我們設置了onClickListener.我們看下他 的源碼
 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;
    }
</pre>
- View的longClickable屬性默認都為false,clickable屬性要分情況,比如Button的clickable屬性默認為true,而TextView的clickable屬性默認為false.但是我們通過setOnLongClickable和setOnClickable可以分別改變View的Clickable和Long_Clickable屬性通過setOnLongClickListener和setOnClickListeren會自動把View的Long_Clickabel和View的Clickable屬性設置為true,這一點可以通過源碼來解釋
<pre>
public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }
public void setOnLongClickListener(@Nullable OnLongClickListener l) {
        if (!isLongClickable()) {
            setLongClickable(true);
        }
        getListenerInfo().mOnLongClickListener = l;
    }
  • 到這里我們基本上把事件分發(fā)給解釋的差不多了,下面我們通過源碼系統(tǒng)的走一邊這個過程,我先用文字的形式走一下
    首先事件會到達頂級的View這個View一般是ViewGroup,這個時候會調用ViewGroup的dispatchTouchEvent()方法,在這個方法里面會調用onInterceptTouchEvent(ev);方法,如果這個方法返回true,那么事件就會由ViewGroup處理,這個時候如果ViewGroup的mOnTouchListener被設置則onTouch方法會被調用,否則,onTouchEvent方法被調用,也就是說如果mOnTouchListener被提供的話onTouch會屏蔽掉onTouchEvent方法(這個我稍后會借助源碼進行分析)在onTouchEvent方法中如果設置了mOnClickListener.,則onClick()方法會被調用. 如果頂級的ViewGroup不攔截事件,那么事件就會傳給他的子view,這個時候子View的dispatchTouchEvent()方法會被調用,如果子View的mOnTouchListener被設置則onTouch方法會被調用,這個時候怎么處理還要看OnTouch的返回值,如果返回false當前的onTouchEvent方法被調用,如果返回true當前的onTouchEvent不會被調用,在onTouchEvent方法中,如果子View設置了OnClicalistener,那么他的onClick方法會被調用.當Move事件來的時候還會先走ViewGroup的dispatchTouchEvent(),重新進入分發(fā).

現(xiàn)在我們結合源碼來分析一下

 @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 = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; 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 - 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;
    }
</pre>
上面的是整個ViewGroup的dispatchTouchEvent()方法,比較長,我們分段來說
<pre>
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;
            }
  • 這段代碼解釋的就是,ViewGroup在如下兩種情況下會判斷是不是要攔截當前事件:第一個條件是這個事件是Down事件,第二個條件是mFirstTouchTarget != null,Down事件比較容易理解,mFirstTouchTarget != null在什么時候不為null呢?通過分析后面的代碼,當事件由ViewGroup的子元素成功處理時 mFirstTouchTarget 會被賦值并指向子元素,這個時候才不為null,當Down事件來的時候ViewGroup會判斷一下是不是要攔截,如果攔截,當Move和Up事件來的時候第一條和第二條都不成立,所以不會在調用onInterceptTouchEvent(ev);方法判斷是否要攔截如果ViewGroup不攔截的時候,這個 時候事件會傳給子View,mFirstTouchTarget 會被賦值并指向子元素,當Move和Up來的時候,會重新調用ViewGroup的dispatchTouchEvent().這個時候第一條就不成立,不是Down事件了,但是第二條成立了,還會調用onInterceptTouchEvent(ev);判斷是否要攔截事件,因為這句話final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;默認返回的是false,我們在上面第11條的時候提到過子View可以通過requestDisallowInterceptTouchEvent()方法改變父View是否要攔截,改變的就是disallowIntercept的值,但是當我們設置了true的時候,ViewGroup將不會攔截除了Down事件以外的事件,因為在上面沒有說,這里我們解釋一下,看一段源碼:
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();
            }
  • 這段代碼要比我們上面分析的代碼調用的時間早,在resetTouchState();這個方法中FLAG_DISALLOW_INTERCEPT;這個標記位會被重置,所以在ViewGroup收到Down事件的時候final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;這段代碼永遠都是false

繼續(xù)分析,看下面的源碼

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 = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; 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 - 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;
                            }
  • 當ViewGroup不攔截事件的時候,ViewGroup會遍歷的子View,然后判斷子View是否能接收點擊事件,是否能接收點擊事件通過兩點來判斷,第一點是子View是否在播放動畫,第二點是點擊的坐標是否落在了子View上,如果這兩點滿足,事件就會給這個子View來處理,dispatchTransformedTouchEvent()注意一下這個方法,這個方法內部就是調用了子View的dispatchTouchEvent()方法,如果子View的dispatchTouchEvent()返回的是true,就會跳出for循環(huán),如果子View的dispatchTouchEvent()返回了false,就將繼續(xù)遍歷下一個子View.這個時候事件就傳遞給了子View,下面我們分析一下子View的事件

下面這段源碼是子View的dispatchTouchEvent();

 public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }
        boolean result = false;
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }
        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // 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, 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;
    }</pre>
上面的源碼有點長,我們精簡一下
<pre>
public boolean dispatchTouchEvent(MotionEvent event) {
   
        boolean result = false;
        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, 0);
        }
        return result;
    }

我們刪除了一些對我們沒有用的東西

通過上面的源碼,可以發(fā)現(xiàn)子View的事件分發(fā)就簡單多了,因為子View沒有涉及到分發(fā),而是自己處理事件,從源碼中可以看出,子View會首先判斷有沒有設置mOnTouchListener,如果設置了就會調用mOnTouchListener.onTouch();如果onTouch方法返回了true,那么子View的dispatchTouchEvent()方法就直接返回了true,這個時候下面的onTouchEvent(event)方法將不會被調用,如果onTouch返回的是false,那么第一個if不成立,就會走第二個if;就會調用onTouchEvent(event)方法,onTouchEvent我們在上面以經分析過了,基本一樣的,這個時候我們的事件分發(fā)到此結束.

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容