1. 程式人生 > >自定義View(二)View的事件分發機制原始碼解析

自定義View(二)View的事件分發機制原始碼解析

View的事件分發機制是Android中的一個難點,也是非常重要的知識點,充分理解和掌握事件分發機制有助於我們在自定義view的過程中更好地設計和解決事件相關問題。下面我們通過原始碼的角度去分析一下Android是怎麼處理view事件的。

一個事件(比如手指按下螢幕的down事件)首先傳遞到activity,它的大致傳遞順序是Activity->Window->View,即先從activity的dispatchTouchEvent開始進行事件分發,具體是由activity內部的Window來完成的,Window再將事件傳遞給decor view,decor view是頂級view的父容器,頂級view就是我們在onCreate方法中的setContentView所設定的view,一般是一個ViewGroup。到達頂級view以後,假設我們的頂級view是一個ViewGroup,那麼此時就會呼叫ViewGroup的dispatchTouchEvent方法將事件分發下去。因為有一個很重要的地方,就是ViewGroup的dispatchTouchEvent方法和view的dispatchTouchEvent方法處理事件的機制是完全不一樣的,所以我們這裡先從ViewGroup的dispatchTouchEvent方法開始,進行事件分發的分析。

首先我們來看看ViewGroup的dispatchTouchEvent方法原始碼,程式碼有點長,我抽取關鍵程式碼貼出來,如下:

public boolean dispatchTouchEvent(MotionEvent ev) {

       // 省略部分程式碼..............

        // Check for interception. 
        // mFirstTouchTarget 代表是否有子view消費了事件
        final boolean intercepted; //是否攔截事件
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                //呼叫了攔截事件的方法,返回Boolean代表是否攔截事件,ViewGroup一般預設不攔截事件
                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的子view,逐一詢問子view是否要消費事件
                final int childrenCount = mChildrenCount; //子view個數
                // 
                if (newTouchTarget == null && childrenCount != 0) {
                    final float x = ev.getX(actionIndex);
                    final float y = ev.getY(actionIndex);
                    // Find a child that can receive the event.
                    // Scan children from front to back.
                    final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;

                    //迴圈遍歷子view
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = getAndVerifyPreorderedIndex(
                                childrenCount, i, customOrder);
                        final View child = getAndVerifyPreorderedView(
                                preorderedList, children, childIndex);

                        // If there is a view that has accessibility focus we want it
                        // to get the event first and if not handled we will perform a
                        // normal dispatch. We may do a double iteration but this is
                        // safer given the timeframe.
                        if (childWithAccessibilityFocus != null) {
                            if (childWithAccessibilityFocus != child) {
                                continue;
                            }
                            childWithAccessibilityFocus = null;
                            i = childrenCount - 1;
                        }

                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                        newTouchTarget = getTouchTarget(child);
                        if (newTouchTarget != null) {
                            // Child is already receiving touch within its bounds.
                            // Give it the new pointer in addition to the ones it is handling.
                            newTouchTarget.pointerIdBits |= idBitsToAssign;
                            break;
                        }

                        resetCancelNextUpFlag(child);
                         // 方法dispatchTransformedTouchEvent是將事件分發給當前child,返回值代表child是否消費了事件,
                         //如果child為null,就會呼叫ViewGroup父類view的dispatchTouchEvent方法,代表當前ViewGroup是
                         //否消費此事件,因為這裡child不為null,所以這裡返回的是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 賦值,就代表有子view消費了事件
                            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.
        //如果沒有子view消費事件,那麼就呼叫view的dispatchTouchEvent方法,因為下面方法中child為null的
        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;
                //如果事件已經傳遞並且被當前子view消費的,那麼就handled為true,那麼當前方法就返回true
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    handled = true;
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
                    //傳遞給當前target的child,看是否消費事件
                    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;
}

在上面ViewGroup的dispatchTouchEvent原始碼中,我們首先判斷是否要呼叫攔截方法onInterceptTouchEvent詢問是否攔截事件,可以看到在down事件或者有子view消費事件的時候,而且又允許攔截的情況下,會呼叫onInterceptTouchEvent方法,就是說mFirstTouchTarget ==null的時候,代表ViewGroup要處理事件序列,此時我們將不再需要呼叫攔截方法詢問是否攔截了。

接下來就是迴圈遍歷ViewGroup的所有child了,首先從是將事件分發給最後一個子view,即最後新增的那個子view,通過dispatchTransformedTouchEvent方法將事件分發,注意這個方法有個引數child,當child不等於null的時候,就會呼叫child的dispatchTouchEvent方法,返回值代表child是否消費了事件,然後我們通過newTouchTarget = addTouchTarget(child, idBitsToAssign)給newTouchTarget賦值,此時就代表有子view消費事件了,然後跳出迴圈。我們看看dispatchTransformedTouchEvent原始碼如下:

 private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }

在這個方法中很重要的是,判斷child是否為null,很明顯非null的時候,就會將事件分給child,否則交給父類view去處理事件。我們繼續往下看,看程式碼:

if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {

       //省略程式碼..................

        }

上面程式碼可以看到,當mFirstTouchTarget為null的時候,有兩種情況,一種是ViewGroup沒有子view消費事件,另外就是沒有子view,即當前view不是ViewGroup,是一個View,此時dispatchTransformedTouchEvent方法child就是null,然後就會呼叫View類的dispatchTouchEvent,將事件交由其處理。其實到這裡ViewGroup的事件分發機制已經大體清楚了,就是首先會根據條件是否呼叫攔截方法onInterceptTouchEvent詢問是否攔截事件,然後就會遍歷子view逐一去詢問是否消費事件。

上面我們主要分析了ViewGroup的dispatchTouchEvent方法,看到ViewGroup是怎麼進行事件的分發的,下面我們來看看View的dispatchTouchEvent方法是怎麼處理事件的,view的這個方法在兩種情況下會被呼叫,一種是事件分發到最後的view不是ViewGroup,另一種是ViewGroup中沒有子view消費事件,也會呼叫。主要程式碼如下:

//view的處理事件的方法
public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

        boolean result = false;

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

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //首先看我們有沒有設定mOnTouchListener 監聽,如果有就將事件傳遞給它的onTouch方法
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            //程式碼執行到這裡會呼叫onTouchEvent方法,將事件交由它處理
            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;
    }

我們可以看到,如果view設定了onTouchListener監聽,會將事件先交由它的onTouch方法處理,然後如果沒有消費的話再交給onTouchEvent去處理,下面我們看看onTouchEvent方法的部分原始碼:

  public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        //是否可以點選
        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        //省略程式碼。。。。。。。。。。。。。。。。。

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }

                    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;
                
            //省略程式碼。。。。。。。。。。。。。。。。 

      
            }

            return true;
        }

        return false;
    }

我們這裡主要看up事件,如果view是可以點選的話,我們在這裡會執行performClick方法,可以看到如果view是可點選的或者可長按的,onTouchEvent就會返回true,否則返回false,false就代表此事件沒有被消費。

通過上面的總結分析,我們主要掌握ViewGroup和View的dispatchTouchEvent方法是怎麼對事件進行處理的,理解了它們的處理機制也就基本掌握了事件分發機制了。下面我們總結一下,我們在自定義view的過程中,經常會碰到的一些需求處理:

  1. 如果我們需要在ViewGroup中攔截事件並且不讓事件向下分發,那麼我們可以重寫onInterceptTouchEvent方法,然後重寫onTouchEvent方法,在onTouchEvent方法中處理事件

  2. 如果我們需要在ViewGroup中處理事件,但是不攔截事件,那麼就重寫dispatchTouchEvent方法,在此方法中處理事件

  3. 處理滑動衝突的時候,我們重寫onInterceptTouchEvent方法,根據具體業務邏輯判斷是否攔截事件,也可以重寫dispatchTouchEvent方法,所有事件先傳給子view,如果子view需要就消費,不需要就返回給父容器的onTouchEvent方法消費。