View的事件傳遞原理和源碼分析

本文將將接View的事件傳遞機制,通過本文的學習,將能夠更好的自定義出我們想要的View。

一、點擊事件的傳遞規則

在講解源碼之前,我們首先介紹一下我們比較熟知的三個方法。

public boolean dispatchTouchEvent(MotionEvent ev)

用於事件的分發,如果事件傳遞到此View,那麼一定會調用此方法,返回結果受到onInterceptTouchEvent和onTouchEvent的返回值影響

public boolean onInterceptTouchEvent(MotionEvent ev)

用於事件的攔截,如果當前View攔截了某個事件,那麼在同一個事件序列當中,此方法不會被再次調用,返回結果表示是否攔截當前事件。

public boolean onTouchEvent(MotionEvent event)

在dispatchTouchEvent方法中調用,用來處理點擊事件,返回結果表示是否消耗當前事件愛你,如果不消耗,則在同一事件序列中,當前View無法再次收到事件。

關於事件傳遞機制,這裏給出一些結論,根據這些結論可以更好的理解整個傳遞機制:(摘自《Android開發藝術探索》)

(1)同一個事件序列是從手指觸摸屏幕的那一刻起,到手指離開屏幕的那一刻結束。在這個過程產生的一系列事件,這個事件序列以down事件開始,中間含有數量補丁的move事件,最終以up事件結束。

(2)正常情況下,一個事件序列只能被一個View攔截且消耗,因爲一旦一個元素攔截了某個事件,那麼同一事件序列中的其他事件將會直接交給它處理,因此同一事件序列中的事件不能分別由兩個View同時處理,但是通過特殊手段可以做到,比如一個View將本該自己處理的事件通過onTouchEvent強行傳遞給其他View處理。

(3)某個View一旦決定攔截,那麼這一個事件序列都只能由它來處理(如果事件序列能夠傳遞給它的話),並且這個View的onInterceptTouchEvent不會再被調用。這條也好理解,就是說當一個View決定攔截一個事件後,那麼系統會把同一事件序列內的其他方法都直接交給它來處理,因此不用再調用這個View的onInterceptTouchEvent去詢問它是否要攔截了。

(4)某個View一旦開始處理事件,如果它不消耗ACTION_DOWN事件(onTouchEvent返回了false),那麼同一事件序列中的其他事件都不會再交給它來處理,並且事件重新交由它的父元素去處理,及父元素的onTouchEvent將會被調用。意思是事件一旦交給一個View處理,那麼它就必須消耗掉,否則同一事件序列中的其他事件不會再交給他處理

(5)如果View不消耗除ACTOION_DOWN以外的其他事件,那麼這個點擊事件將會消失,此時父元素的onTouchEvent並不會被調用,並且當前View可以持續受到後續的實踐,最終這個消失的點擊事件會傳遞給Activity處理。

(6)ViewGroup默認不攔截任何事件,Android源碼中ViewGroup的onInterceptTouchEvent方法默認返回false。

(7)View沒有onInterceptTouchEvent方法,一旦有點擊事件傳遞給他,那麼他的onTouchEvent方法就會被調用

(8)View的onTouchEvent默認會消耗事件(return true),除非它是不可點擊的(clickable和longClickable同時爲false),View的longClickable屬性默認爲false,clickable屬性要分情況,比如Button的clickable屬性默認爲true,而TextView的clickable屬性默認爲false。

(9)View的enable屬性不影響onTouchEvent的默認返回值,哪怕一個View是disable狀態,只要它的clickable或者longClickable有一個爲true,那麼它的onTouchEvent就返回true

(10)onClick會發生的前提是當前View是可點擊的,並且它收到了down和up的事件

(11)事件傳遞過程總是從外向內的,即事件總是先傳遞給父元素,然後再由父元素分發給View,通過requestDisallowInterceptTouchEvent方法可以在子元素中干預父元素的事件分發過程,但是ACTION_DOWN事件除外。

二、事件傳遞源碼分析

1、activity對點擊事件的分發過程

activity的源碼起始是在dispatchTouchEvent開始,其源碼如下:

public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}

從源碼中我們可以看出,activity的dispatchTouchEvent會調用getWindow().superDispatchTouchEvent,其實是調用PhoneWindow的superDispatchTouchEvent,如果superDispatchTouchEvent返回false,也就是這個事件沒有View去處理,那麼就會調用Activity的onTouchEvent

我們再看PhoneWindow的superDispatchTouchEvent源碼:

@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

這個調用了DecorView的superDispatchTouchEvent,

DecorView源碼:

public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

繼續調用了super.dispatchTouchEvent,DecorView是FrameLayout的子類,FrameLayout是ViewGroup的子類,最終調用了ViewGroup的dispatchTouchEvent方法

我們來看ViewGroup的dispatchTouchEvent,由於代碼比較長,我們先只看一段::

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

這段主要是傳遞前做一些清理重置工作,重置一些比較重要的標記,比較重要的是置空mFirstTouchTarget(如果有子View處理事件則會被賦值)和清除FLAG_DISALLOW_INTERCEPT標記(通過requestDisallowInterceptTouchEvent設置的標記)

再繼續往下看:

final boolean intercepted;

//如果是down事件或者mFirstTouchTarget不等於空

if (actionMasked == MotionEvent.ACTION_DOWN

|| mFirstTouchTarget != null) {

//並且當前View並沒有設置不允許攔截,則會執行onInterceptTouchEvent,down事件肯定會執行這個方法,因爲上面我們說了,down事件會重置FLAG_DISALLOW_INTERCEPT標記,此時intercepted由onInterceptTouchEvent決定

final boolean intercepted;
//如果是down事件或者mFirstTouchTarget不等於空
if (actionMasked == MotionEvent.ACTION_DOWN
        || mFirstTouchTarget != null) {
//並且當前View並沒有設置不允許攔截,則會執行onInterceptTouchEvent,down事件肯定會執行這個方法,因爲上面我們說了,down事件會重置FLAG_DISALLOW_INTERCEPT標記,此時intercepted由onInterceptTouchEvent決定
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
    if (!disallowIntercept) {
        intercepted = onInterceptTouchEvent(ev);
        ev.setAction(action); // restore action in case it was changed
    } else {
//如果不允許當前View攔截,則intercepted爲false
        intercepted = false;
    }
} else {
    // There are no touch targets and this action is not an initial down
    // so this view group continues to intercept touches.
//如果沒有子View處理此事件,也就是mFirstTouchTarget爲空,並且不是down事件,也就是一次點擊事件的後續事件,包括move和up事件,那麼intercepted爲true,表示當前View攔截了這個事件
    intercepted = true;
}

從這段代碼可以看出,說明已經在註釋中寫的很清楚

繼續往下看

TouchTarget newTouchTarget = null;
//如果沒有取消,並且當前View沒有攔截
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;
//如果是down事件
    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;
//如果newTouchTarget爲空,並且有子View,則會遍歷ViewGroup的所有子元素,然後判斷子元素是否能夠接受到點擊事件。是否能夠接收點擊事件主要有兩點衡量:子元素是否在播放動畫和點擊事件是否落在子元素的區域內。
        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);

               //......省略部分代碼.......
//比較重要的是dispatchTransformedTouchEvent方法,是調用子元素的dispatchTouchEvent
                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();
//給mFirstTouchTarget賦值
                    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();
        }

     //...............省略部分代碼...........
    }
}

上述代碼是遍歷子元素,判斷是否有子元素處理事件,如果有,則給mFirstTouchTarget賦值,我們來看看

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

    // 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 == 0) {
        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 {
                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()) {
            transformedEvent.transform(child.getInverseMatrix());
        }

        handled = child.dispatchTouchEvent(transformedEvent);
    }

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

其實最核心的就是判斷如果child == null,則調用super.dispatchTouchEvent,也就是View的dispatchTouchEvent,否則就會調用子元素的dispatchTouchEvent,將事件傳遞下去。我們再回到ViewGroup的dispatchTouchEvent中來,如果dispatchTransformedTouchEvent返回true,也就是有子元素處理了此down事件,那麼就會在addTouchTarget中給mFirstTouchTarget賦值,否則,就會有如下判斷

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

如果mFirstTouchTarget == null,也就是沒有子元素處理,那麼就會被當前元素處理(child參數傳了null,在裏面會遞交給啊當前View處理)

那麼目前down事件我們已經講解完了,move事件和up事件也按照同樣的道理往下傳遞

下面我們來看看View的dispatchTouchEvent處理

public boolean dispatchTouchEvent(MotionEvent event) {
 //.....................省略部分代碼..............
    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;
        }
    }
//...................省略部分代碼....................

    return result;
}

代碼很簡單,主要是判斷是否設置onTouchListener事件,如果設置了,並且當前View是enable的,並且onTouchListener裏面的onTouch返回了true,那麼dispatchTouchEvent返回true,並且不會走onTouchEvent事件,說明onTouchListener的優先級比onTouchEvent高

如果當前View是disable的或者沒有設置onTouchListener或者onTouch返回了false,那麼就會調用onTouchEvent事件,根據onTouchEvent的返回值,決定當前View是否消耗此事件。

我們來看看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();
//如果當前View是disabled的,那麼就會根據當前View是否是Clickable或者longClickable來返回是否消耗此事件
    if ((viewFlags & ENABLED_MASK) == DISABLED) {
        if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
            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;
        }
    }
//如果當前View是enable,並且是Clickable或者longClickable等,就會進入如下判斷
    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)) {
//會在up事件中響應onClickListener事件
                                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;
}

以上就是View的onTouchEvent,是否enable不決定當前View是否消耗此事件,clickable纔是決定消耗事件的關鍵,如果當前View消耗了down事件,那麼就會在up事件響應onClick事件,說明onClick的優先級比onTouchEvent低

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