Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> ViewGroup的dispatchTouchEvent理解

ViewGroup的dispatchTouchEvent理解

編輯:關於Android編程

以下圖例子說明,OFramelayout在最外層

這裡寫圖片描述

    圖1.1 view的層級關系

結論1:
dispatchTouchEvent()返回false,後續的ACTION_MOVE、ACTION_UP等收不到。注:dispatchTouchEvent()中判斷手勢是
ACTION_DOWN時,返回false,則後續的觸摸事件收不到,如果返回true,在後續的ACTION_MOVE條件下,不論返回什麼都能收到後續觸摸響應。類推,在onTouchEvent中是一樣的結論。

結論2:
如果有對應的OnTouchListener,可以在onTouch中返回true攔截事件,使onTouchEvent()不執行。

結論3:
在一次觸摸事件中,如果onInterceptTouchEvent()中返回true,則觸摸事件由該視圖消費,不會再派發。如果onInterceptTouchEvent()先返回false,然後在某個條件返回true,則在起初返回false時,onInterceptTouchEvent()會被一直調用(前提條件是子視圖消費了事件並返回了true),返回true後,onInterceptTouchEvent將不會再被調用,不管以後返回啥,onInterceptTouchEvent都不會再被調用。注:前提條件是該視圖的dispatchTouchEvent要返回true,也就是說要能持續響應觸摸事件。

看到這,大家都會覺得雲裡霧裡,通過研讀源碼具體分析每個結論,以下基於android 5.0的源碼。

結論一研讀:

MFramelayout在dispatchTouchEvent()中的ACTION_DOWN條件下返回false,則觸控事件首先進入OFramelayout的dispatchTouchEvent()即ViewGroup的dispatchTouchEvent()。進入1956行的判斷,disallowIntercept是由requestDisallowInterceptTouchEvent()方法決定的。disallowIntercept為false時表示可攔截事件,然後會調用onInterceptTouchEvent()方法。disallowIntercept默認時為false。然後進入1985行的判斷,由於是ACTION_DOWN,繼續進入1995行,繼續進入2007行,繼續進入2016的for循環,進入2049的條件判斷。進入dispatchTransformedTouchEvent()方法,在該方法的2405行,handled = child.dispatchTouchEvent(event),也就是調用了MFramelayout的dispatchTouchEvent()方法,由於假定條件下其返回false,dispatchTransformedTouchEvent()該方法返回false,這樣就不會進入2049行的條件。然後進入到2090的條件判斷,還是調用了dispatchTransformedTouchEvent()方法,然後執行super.dispatchTouchEvent(event),也就是執行View.dispatchTouchEvent()方法。關於View.dispatchTouchEvent(),請查看郭霖的博客。在OFramelayout的onTouchEvent中返回true,則2092行的handled為true,那麼OFrameLayout的dispatchTouchEvent返回true。
接下來觸摸事件是ACTION_MOVE,進入到OFrameLayout的dispatchTouchEvent()方法。進入到1968行,intercepted = true,則不會進入1985的條件判斷,接下來進入2090行的條件判斷。在這個過程中,OFrameLayout沒將事件傳給子視圖。也就是dispatchTouchEvent()方法在ACTION_DOWN時返回false,則收不到後續的觸摸事件,在這裡就是MFramelayout收不到後續事件。

結論2研讀:

查看郭霖的博客。Android事件分發機制完全解析,帶你從源碼的角度徹底理解(上),
Android事件分發機制完全解析,帶你從源碼的角度徹底理解(下)

結論3研讀

情況一:OFramelayout的onInterceptTouchEvent返回true。

OFrameLayout的dispatchTouchEvent()接受觸控事件,ACTION_DOWN時會執行1960-》2092。mFirstTouchTarget為null,其賦值在2065行的addTouchTarget()方法中。ACTION_MOVE時執行1968-》2092。所以,在一次觸摸事件中,如果onInterceptTouchEvent()中返回true,則觸摸事件由該視圖消費,不會再派發。

情況二:OFramelayout的onInterceptTouchEvent返回false。

ACTION_DOWN時,執行1960-》1985-》1995-》2049,假設子視圖消費了事件並返回了true,則會執行2065行,則mFirstTouchTarget被賦值為該子視圖。
ACTION_MOVE是,在上面假設下,mFirstTouchTarget不為空,則會調用onInterceptTouchEvent()方法。執行順序1960-》1985,由於是ACTION_MOVE,則不會進1995,接下來到2097-》2106,然後執行子視圖(MFramelayout)的dispatchTouchEvent()方法。
如果子視圖沒有消費事件,則mFirstTouchTarget為空,則onInterceptTouchEvent()只會執行一次。
所以onInterceptTouchEvent()返回false,會被一直調用(前提條件是子視圖消費了事件並返回了true)。

情況三:在一次觸摸事件中,OFramelayout的onInterceptTouchEvent返回false,在某個條件再返回true。

在OFramelayout的onInterceptTouchEvent返回false時,詳情參考情況二。在某個條件下onInterceptTouchEvent返回true時,假設先前子視圖消費了事件並返回了true(即mFirstTouchTarget不為空),會執行1960-》2097-》2375-》2112,在2112行mFirstTouchTarget被賦值為null。觸摸事件繼續執行1968-》2092,onInterceptTouchEvent不會再被調用。
所以如果onInterceptTouchEvent()先返回false,然後在某個條件返回true,則在起初返回false時,onInterceptTouchEvent()會被一直調用(前提條件是子視圖消費了事件並返回了true),返回true後,onInterceptTouchEvent將不會再被調用,不管以後返回啥,onInterceptTouchEvent都不會再被調用。

ViewGroup的dispatchTouchEvent源碼

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 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;
    }
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved