Android觸摸屏ViewGroup事件派發機制詳解與源碼分析

同樣的還是參考了一些文章,在我上一篇文章中的頭部:
http://blog.csdn.net/lijinhua7602/article/details/51122214

2 基礎實例現象

2-1 例子

這個例子佈局等還和上一篇的例子相似,只是重寫了Button和LinearLayout而已,具體參見上一篇:
首先我們簡單的自定義一個Button(View的子類),再自定義一個LinearLayout(ViewGroup的子類),其實沒有自定義任何屬性,只是重寫部分方法(添加了打印,方便查看)而已,如下:

<?xml version="1.0" encoding="utf-8"?>
<com.example.viewdispatch.ViewGroupLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mylayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.example.viewdispatch.ViewGroupTestButton
        android:id="@+id/my_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click test" />

</com.example.viewdispatch.ViewGroupLinearLayout>
public class ViewGroupTestButton extends Button {

    public ViewGroupTestButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_down --");
            break;
        case MotionEvent.ACTION_MOVE:
        Log.i(ListenerActivity.TAG, "dispatchTouchEvent--- action_move --");
            break;
        case MotionEvent.ACTION_UP:
        Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_up --");
            break;
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            Log.i(ListenerActivity.TAG, "onTouchEvent-- action_down --");
            break;
        case MotionEvent.ACTION_MOVE:
            Log.i(ListenerActivity.TAG, "onTouchEvent-- action_move --");
            break;
        case MotionEvent.ACTION_UP:
            Log.i(ListenerActivity.TAG, "onTouchEvent--action_up --");
            break;
        }
        return super.onTouchEvent(event);
    }
}
public class ViewGroupListenerActivity extends Activity implements View.OnTouchListener, View.OnClickListener {


    private ViewGroupLinearLayout mLayout;
    private ViewGroupTestButton mButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.viewgroup_listener);

        mLayout = (ViewGroupLinearLayout) this.findViewById(R.id.mylayout);
        mButton = (ViewGroupTestButton) this.findViewById(R.id.my_btn);

        mLayout.setOnTouchListener(this);
        mButton.setOnTouchListener(this);

        mLayout.setOnClickListener(this);
        mButton.setOnClickListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        Log.i(ListenerActivity.TAG, "OnTouchListener--onTouch-- action_down --" + v);
            break;
        case MotionEvent.ACTION_MOVE:
        Log.i(ListenerActivity.TAG, "OnTouchListener--onTouch-- action_move --" + v);
            break;
        case MotionEvent.ACTION_UP:
        Log.i(ListenerActivity.TAG, "OnTouchListener--onTouch-- action_up --" + v);
            break;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        Log.i(ListenerActivity.TAG, "OnClickListener--onClick--" + v);
    }
}

2-2 運行現象
這裏寫圖片描述

分析:
你會發現這個結果好驚訝吧,點擊了Button卻先執行了ViewGroupLinearLayout(ViewGroup)的dispatchTouchEvent,接着執行ViewGroupLinearLayout(ViewGroup)的onInterceptTouchEvent,接着執行ViewGroupTestButton(ViewGroupLinearLayout包含的成員View)的dispatchTouchEvent,接着就是View觸摸事件的分發流程,上一篇已經講過了。也就是說當點擊View時事件派發每一個down,up的action順序是先觸發最父級控件(這裏爲LinearLayout)的dispatchTouchEvent->onInterceptTouchEvent->然後向前一級傳遞(這裏就是傳遞到Button View)。

那麼繼續看,當直接點擊除Button以外的其他部分時打印如下:
這裏寫圖片描述

分析:你會發現一個奇怪的現象,派發ACTION_DOWN(action=0)事件時順序爲dispatchTouchEvent->onInterceptTouchEvent->onTouch->onTouchEvent,而接着派發ACTION_UP(action=1)事件時與上面順序不同的時竟然沒觸發onInterceptTouchEvent方法。這是爲啥呢?我也納悶,那就留着下面分析源碼再找答案吧,先記住這個問題。

有了上面這個例子你是不是發現包含ViewGroup與View的事件觸發有些相似又有很大差異吧(PS:在Android中繼承View實現的控件已經是最小單位了,也即在XML佈局等操作中不能再包含子項了,而繼承ViewGroup實現的控件通常不是最小單位,可以包含不確定數目的子項)。具體差異是啥呢?咱們類似上篇一樣,帶着這個實例疑惑去看源碼找答案吧。

ViewGroup觸摸屏事件傳遞源碼分析

從ViewGroup的dispatchTouchEvent方法說起

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
      // mInputEventConsistencyVerifier是調試用的,不會理會
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
     // 第1步:是否要分發該觸摸事件
    // onFilterTouchEventForSecurity()表示是否要分發該觸摸事件。 
    // 如果該View不是位於頂部,並且有設置屬性使該View不在頂部時不響應觸摸事件,則不分發該觸摸事件,即返回false。
    // 否則,則對觸摸事件進行分發,即返回true。
        // 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);
        }
        // 該View被遮蔽,並且該View在被遮蔽時不響應點擊事件
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
        // 第2步:檢測是否需要清空目標和狀態
        // 如果是ACTION_DOWN(即按下事件),則清空之前的觸摸事件處理目標和狀態。
        // 這裏的情空狀態包括:
        // (01) 清空mFirstTouchTarget鏈表,並設置mFirstTouchTarget爲null。
        //mFirstTouchTarget是"接受觸摸事件的View"所組成的單鏈表
       // (02) 清空mGroupFlags的FLAG_DISALLOW_INTERCEPT標記
        //如果設置了FLAG_DISALLOW_INTERCEPT,則不允許          ViewGroup對觸摸事件進行攔截。
        // (03) 清空mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVEN標記
            // 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;
    }

第一步,ACTION_DOWN進行處理。
30-36行,ACTION_DOWN(即按下事件),則清空之前的觸摸事件處理目標和狀態,清空mFirstTouchTarget鏈表,並設置mFirstTouchTarget爲null, 清空mGroupFlags的FLAG_DISALLOW_INTERCEPT標記,清空mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVEN標記

第二步,40-53行,檢查是否要攔截,設置intercepted。
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) 是按下事件,或者這個Touch的目標組件不爲null,進入到裏面,否則就設置intercepted爲true,我們來看進入到裏面的情況,這裏有一個變量FLAG_DISALLOW_INTERCEPT,這個是檢查是否禁止攔截標記,來看一下這個變量相關的方法:

    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }

        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }

        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }

調用這個方法requestDisallowInterceptTouchEvent(true); 阻止ViewGroup對其MOVE或者UP事件進行攔截,則intercepted直接設置爲false,否則調用onInterceptTouchEvent(ev)方法,然後將結果賦值給intercepted,來看一下 onInterceptTouchEvent(ev)方法,

public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

默認的onInterceptTouchEvent方法只是返回了一個false,也即intercepted=false。所以可以說明上面例子的部分打印(dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent),這裏很明顯在ViewGroup的dispatchTouchEvent()中默認(不在其他地方調用requestDisallowInterceptTouchEvent方法設置FLAG_DISALLOW_INTERCEPT禁止攔截標記時這個默認爲false,要進行攔截,只不過這裏面的ViewGroup裏面onInterceptTouchEvent方法默認返回false,即intercepted=false)。
第三步,檢查canceled變量是否被取消。
對於ACTION_DOWN而言,mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVENT位肯定是0;因此,canceled=false,所以沒有被取消
第四步,檢查split變量
默認是true,作用是否把事件分發給當前ViewGroup的子View和子ViewGroup,這個同樣在ViewGroup中提供了public的方法設置,如下:

 public void setMotionEventSplittingEnabled(boolean split) {
        // TODO Applications really shouldn't change this setting mid-touch event,
        // but perhaps this should handle that case and send ACTION_CANCELs to any child views
        // with gestures in progress when this is changed.
        if (split) {
            mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
        } else {
            mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
        }
    }

事件分發步驟中關於ACTION_DOWN的特殊處理
if (!canceled && !intercepted)判斷表明,事件不是ACTION_CANCEL並且ViewGroup的攔截標誌位intercepted爲false(不攔截)則會進入其中。進入到裏面首先看第一個if條件:
對於ACTION_DOWN,actionIndex肯定是0,就會進入到if裏面,接下來就是處理點擊事件:這裏面引用到了博客裏面的內容:http://blog.csdn.net/yanbober/article/details/45912661

ViewGroup觸摸屏事件傳遞總結

  1. Android事件分發是先傳遞到ViewGroup,再由ViewGroup傳遞到View的。
  2. 在ViewGroup中可以通過onInterceptTouchEvent方法對事件傳遞進行攔截,onInterceptTouchEvent方法返回true代表不允許事件繼續向子View傳遞,返回false代表不對事件進行攔截,默認返回false。
  3. 子View中如果將傳遞的事件消費掉,ViewGroup中將無法接收到任何事件。

實例現象

現在我們就能解釋上一篇中的TestButton裏面的dispatchTouchEvent返回false的情況,執行了linearlayout的onTouch,因爲TestBuatton裏面的dispatchTouchEvent返回false表示對當前的view不進行分發事件,所以TestBoutton所有的事件都接受不到了

  1. 將ViewGroupLinearLayout的dispatchTouchEvent改爲true,其他基礎代碼不變:
@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout dispatchTouchEvent--action_down --");
            break;
        case MotionEvent.ACTION_MOVE:
            Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout dispatchTouchEvent--action_move --");
            break;
        case MotionEvent.ACTION_UP:
            Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout dispatchTouchEvent--action_up --");
            break;
        }
        return true;
    }

點擊Button或者之外都是一樣的
這裏寫圖片描述

不進行事件的分發,所以只執行當前ViewGorup的dispatchTouchEvent方法

現在我們進行攔截,把ViewGroupLinearLayout的onInterceptTouchEvent返回爲true,其他基礎保持不變:

@Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout onInterceptTouchEvent--action_down --");
            break;
        case MotionEvent.ACTION_MOVE:
            Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout onInterceptTouchEvent--action_move --");
            break;
        case MotionEvent.ACTION_UP:
            Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout onInterceptTouchEvent--action_up --");
            break;
        }
        return true;
    }

點擊Button或者Button之外:
這裏寫圖片描述
分析:因爲 我們這裏面進行了攔截,所以不會執行Button的任何方法,只會執行當前類的OnTouchEvent和onTouch方法

如何不攔截也,我們只需要重寫子類View的dispatchTouchEvent方法,利用requestDisallowInterceptTouchEvent(true)設置不要進行攔截,處理ViewGroupTestButton的dispatchTouchEvent,其他代碼不變:

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        getParent().requestDisallowInterceptTouchEvent(true);
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_down --");
            break;
        case MotionEvent.ACTION_MOVE:
        Log.i(ListenerActivity.TAG, "dispatchTouchEvent--- action_move --");
            break;
        case MotionEvent.ACTION_UP:
        Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_up --");
            break;
        }
        return super.dispatchTouchEvent(event);
    }

這裏寫圖片描述

分析可以看到ViewGroupLinearLayout的onToucheEvent沒有執行,更多請讀者自選嘗試

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