Android View相關-事件分發機制詳解-ViewGroup

上一篇文章中,我們從一個小例子和源碼角度解析了View的事件分發過程,我們知道其執行流程是dispathcEvent -> onTouch -> onTouchEvent,在onTouchEvent中會經過判斷處理OnClick事件和OnLongClick事件。那麼本文我們來探討下View的子類ViewGroup的事件分發流程。

舉個栗子

這裏使用一個自定義LinearLayout和一個自定義Button,自定義Button就是上一篇文章中的button,貼出代碼:

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

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

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

@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    Log.e(TAG, "requestDisallowInterceptTouchEvent disallowIntercept"+disallowIntercept);
    super.requestDisallowInterceptTouchEvent(disallowIntercept);
}

同樣是簡單地打印了幾個log,我們來看下在xml文件中的佈局:

<com.xylitolz.androideventdispatchdemo.TestLinearLayout
        android:id="@+id/ll_test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center_horizontal">
        <com.xylitolz.androideventdispatchdemo.TestButton
            android:id="@+id/view_test_in_container"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textAllCaps="false"
            android:text="testInContainer"/>
    </com.xylitolz.androideventdispatchdemo.TestLinearLayout>

就是使用自定義LinearLayout包裹自定義Button,那麼我們直接來看看執行結果,首先是點擊事件:

接下來是點擊然後輕微移動,之後手指離開屏幕:

可以看到其執行流程是先從ViewGroup開始的,首先是ViewGroup dispatchTouchEvent —-> ViewGroup onInterceptTouchEvent —-> 子View dispatchTouchEvent —-> 子View onTouch —-> 子View onTouchEvent 若有move事件則是ACTION_DOWN —-> ACTION_MOVE —-> ACTION_UP的流程,接下來我們就從源碼角度對這一執行順序進行分析。

源碼分析

dispatchTouchEvent

和前文一樣,我們從dispatchTouchEvent開始分析,ViewGroup中的該方法代碼較多

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

這裏將整個步驟分解爲四部,首先看第一部分:

  • step1

    這一部分主要是當TouchEvent爲ACTION_DOWN時進行一些初始化操作,例如重設觸摸狀態、開始新的手勢等,若有興趣可以查看cancelAndClearTouchTargetsresetTouchState源碼

  • step2

    檢查是否需要攔截Touch事件,核心方法onInterceptTouchEvent,這裏生成了一個局部變量intercepted後續也會用它來判斷是否攔截,這個值會被onInterceptTouchEvent的返回值所改變。

  • step3

    該事件Action爲ACTION_DOWN並且mFirstTouchTarget值不爲null,則繼續if語句中的代碼,那麼mFirstTouchTarget是幹嘛的。mFirstTouchTarget是TouchTarget類的對象,而TouchTarget是ViewGroup中的一個內部類,它封裝了被觸摸的View及這次觸摸所對應的ID,該類主要用於多點觸控。比如:三個指頭依次按到了同一個Button上。 我們需要重點關注mFirstTouchTarget,因爲它也貫穿了整個dispatchTouchEvent方法中。若mFirstTouchTarget不爲空,表示ViewGroup沒有攔截Touch事件並且子View消費了Touch;若mFirstTouchTarget爲空,則表示ViewGroup攔截了Touch事件或者雖然ViewGroup沒有攔截Touch事件但是子View也沒有消費Touch。此時需要ViewGroup自身處理Touch事件。

    若(mFirstTouchTarget!=null),當處理後續到來的ACTION_MOVE和ACTION_UP時仍會調用該代碼判斷是否需要攔截Touch事件。

    接下來開始遍歷所有的子View

    判斷當前的x,y座標是否落在子View身上,如果在,執行child.dispatchTouchEvent(ev),就進入了View的dispatchTouchEvent代碼中了,當child.dispatchTouchEvent(ev)返回true,則爲mMotionTarget設爲child,然後return true;

    ViewGroup實現捕獲到DOWN事件,如果代碼中不做TOUCH事件攔截,則開始查找當前x,y是否在某個子View的區域內,如果在,則把事件分發下去。

  • step4

    ACTION_MOVE中,ViewGroup捕獲到事件,然後判斷是否攔截,如果沒有攔截,則直接調用mMotionTarget.dispatchTouchEvent(ev)

  • step5

    ACTION_UP中,ViewGroup捕獲到事件,然後判斷是否攔截,如果沒有攔截,則直接調用mMotionTarget.dispatchTouchEvent(ev)

onInterceptTouchEvent

攔截事件

複寫onInterceptTouchEvent並在需要攔截的事件中返回true,則代表事件被當前ViewGroup攔截,則不再下發給子View。

不攔截事件

若父控件複寫了onInterceptTouchEvent方法並在需要攔截的操作裏返回了true,那麼若子View不希望父控件處理該操作,可以在子View中複寫requestDisallowInterceptTouchEvent,返回true則子View仍能獲取到相關操作

小結

本篇流程總結有些混亂,回頭會重新梳理再發出來,暫時先這樣吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章