View事件分發(fā)機制

1泼返、View和ViewGroup之間的關系

在android中,ViewGroup 繼承了View,也就是說android中控件全部是View唠椭,不管是TextView,Button,ImageView還是五大布局等,只不過ViewGroup可以放置其他的View和ViewGroup忍饰,而View是不可以的

2贪嫂、View中的事件序列

在android中,一次操作(點擊艾蓝,觸摸等)會產(chǎn)生一個事件序列力崇,這個事件序列組成部分為:一個MotionEvent.ACTION_DOWN事件,0到多個MotionEvent.ACTION_MOVE事件赢织,一個MotionEvent.ACTION_UP或是MotionEvent.ACTION_CANCEL事件

事件分發(fā)機制涉及的主要方法

dispatchTouchEvent(MotionEvent ev): 對事件進行分發(fā)亮靴,返回值表示是否消費當前事件,返回值受該View的OnTouchEvent()和子View的dispatchTouchEvent()方法返回值影響

onInterceptTouchEvent(MotionEvent ev): 該方法只存在于ViewGroup中于置,返回值表示是否對當前事件進行攔截

onTouchEvent(MotionEvent ev): 該方法返回值表示是否消費當前事件

3茧吊、詳細測試

兩個簡單的view分別為MRelativeLayout extends RelativeLayout和MTextView extends TextView

3.1 測試一:父View對事件攔截,并在onTouchEvent()對事件處理八毯,這個時候父view的dispatchTouchEvent返回值是為true的
QQ截圖20160727152331.png
3.2 測試二:父View對事件攔截搓侄,但在onTouchEvent()對事件沒有處理
QQ截圖20160727154144.png
3.3 測試三:父View對事件不攔截,子View對事件進行處理
QQ截圖20160727164011.png
3.4 測試四:父view對事件不攔截话速,子view對事件也不處理
QQ截圖20160727164637.png
3.5 簡要總結(jié)
public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean isConsume = false;
        if(onInterceptTouchEvent(ev)){
            isConsume = onTouchEvent(ev);
        }else{
            isConsume = childView.dispatchTouchEvent(ev);
        }
        return isConsume;
    }

一個事件產(chǎn)生后讶踪,先由viewgroup的dispatchTouchevent對事件進行分發(fā),dispatchTouchevent先調(diào)用onInterceptTouchEvent查看自己是否攔截了事件泊交, 1): 如果攔截了乳讥,則再看自己的onTouchEvent對事件是否進行了消費處理柱查,如果自己處理了,則返回true云石,事件到這里就結(jié)束了唉工;如果沒有處理,那么該事件則會往父view拋(onTouchEvent)留晚,如果父view都沒有處理酵紫,則拋向window直到activity的onTouchEvent;2) 如果ViewGroup沒有攔截事件错维,則交給子View的dispatchTouchEvent()來進行分發(fā),如果子View也是ViewGroup,分發(fā)邏輯和上面一樣橄唬,如果子View是一個View赋焕,那么則直接進入View的onTouchEvent()來確定事件是否被消耗掉,如果消耗了仰楚,返回true隆判,如果沒有消耗,則依次往父view拋僧界,直到交給activity處理侨嘀。

image.png
4、View源碼分析
4.1 在android中捂襟,當用戶觸摸設備產(chǎn)生事件(MotionEvent)的時候咬腕,事件會先傳遞到activity,然后activity傳給其內(nèi)部的window葬荷,window再傳給decorview涨共,decorview傳給布局中的相關view。
4.2 Activity.dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();// 空實現(xiàn)
        }
        // window初始化在attach()方法中
        if (getWindow().superDispatchTouchEvent(ev)) {
          // 事件被Activity的下級給消費掉了
            return true;
        }
        // 事件在Activity的下級中沒有被消費掉宠漩,交由Activity自己來處理
        return onTouchEvent(ev);
    }
4.3 Window.superDispatchTouchEvent()

Window是一個抽象類举反,根據(jù)Window類的注釋能夠知道,在整個android系統(tǒng)中扒吁,window只有一個子類:PhoneWindow,所以這里主要是看PhoneWindow對這個方法的實現(xiàn)火鼻。

@Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        // mDecor是一個DecorView
        return mDecor.superDispatchTouchEvent(event);
    }

可以看到,PhoneWindow把對事件的處理權限交給了DecorView雕崩,那么DecorView是什么呢魁索?又是怎么初始化的呢?

4.4 DecorView

private final class DecorView extends FrameLayout implements RootViewSurfaceTaker 晨逝,
從這個定義可以看到DecorView其實就是一個FrameLayout而已蛾默。

4.5 DecorView的初始化過程

在activity中設置View是通過setContentView()方法來完成的,所以我們從這里開始分析一下是怎么操作的捉貌。
Activity.setContentView()

public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

PhoneWindow.setContentView()

@Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
          // 這里負責DecorView和mContentParent的初始化支鸡,至于mContentParent冬念,它是:
          // ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
          // ID_ANDROID_CONTENT = com.android.internal.R.id.content
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {// Activity過渡動畫
            view.setLayoutParams(params);
            final Scene newScene = new Scene(mContentParent, view);
            transitionTo(newScene);
        } else {
            // 把我們自己的布局添加到mContentParent容器中
            mContentParent.addView(view, params);
        }
        //.........
    }

PhoneWindow.installDecor()

private void installDecor() {
       private void installDecor() {
        if (mDecor == null) {
            // 初始化DecorView
            mDecor = generateDecor();
            // .........
        }
        if (mContentParent == null) {
            // 初始化ViewGroup,也就是我們定義的布局的父容器
            mContentParent = generateLayout(mDecor);
            // .....................
        }
    }
    

PhoneWindow.generateDecor()

protected DecorView generateDecor() {
        return new DecorView(getContext(), -1);
    }

PhoneWindow.generateLayout()

protected ViewGroup generateLayout(DecorView decor) {
        //............ 

        mDecor.startChanging();
        // 這個名為in的View,用來決定整個window會顯示成什么樣子(Theme),
        View in = mLayoutInflater.inflate(layoutResource, null);
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        mContentRoot = (ViewGroup) in;
        // 從in這個view中找到我們自己定義的布局的父容器
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        if (contentParent == null) {
            throw new RuntimeException("Window couldn't find content container view");
        }
        //....................
        mDecor.finishChanging();
        return contentParent;
    }

這里貼兩個名為in的View對應的布局文件
R.layout.screen_custom_title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:fitsSystemWindows="true">
    <!-- Popout bar for action modes -->
    <ViewStub android:id="@+id/action_mode_bar_stub"
              android:inflatedId="@+id/action_mode_bar"
              android:layout="@layout/action_mode_bar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:theme="?attr/actionBarTheme" />

    <FrameLayout android:id="@android:id/title_container" 
        android:layout_width="match_parent" 
        android:layout_height="?android:attr/windowTitleSize"
        android:transitionName="android:title"
        style="?android:attr/windowTitleBackgroundStyle">
    </FrameLayout>
    <FrameLayout android:id="@android:id/content"
        android:layout_width="match_parent" 
        android:layout_height="0dip"
        android:layout_weight="1"
        android:foregroundGravity="fill_horizontal|top"
        android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>

R.layout.screen_simple.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:fitsSystemWindows="true">
    <!-- Popout bar for action modes -->
    <ViewStub android:id="@+id/action_mode_bar_stub"
              android:inflatedId="@+id/action_mode_bar"
              android:layout="@layout/action_mode_bar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:theme="?attr/actionBarTheme" />
    <FrameLayout
        android:layout_width="match_parent" 
        android:layout_height="?android:attr/windowTitleSize"
        style="?android:attr/windowTitleBackgroundStyle">
        <TextView android:id="@android:id/title" 
            style="?android:attr/windowTitleStyle"
            android:background="@null"
            android:fadingEdge="horizontal"
            android:gravity="center_vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
    <FrameLayout android:id="@android:id/content"
        android:layout_width="match_parent" 
        android:layout_height="0dip"
        android:layout_weight="1"
        android:foregroundGravity="fill_horizontal|top"
        android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>

關于DectorView的初始化過程就是這樣了牧挣,從這里也可以看出來整個View的層級關系:
Activity->window->decorview->SystemLayout->contentView->應用自定義布局對應view

4.6 繼續(xù)事件分發(fā):DecorView.superDispatchTouchEvent()
public boolean superDispatchTouchEvent(MotionEvent event) {
        // 因為DecorView是一個FrameLayout,因而這里就是ViewGroup.dispatchTouchEvent()
            return super.dispatchTouchEvent(event);
        }
4.7 ViewGroup.dispatchTouchEvent()
@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;
        // 是否對事件進行分發(fā)急前,如果窗口被遮擋,直接返回false瀑构,否則返回true
        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.
                // 如果監(jiān)聽到ACTION_DOWN事件裆针,表明一次觸摸的開始,那么一些東西就要清空和重置了寺晌。
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;// 是否對事件進行了攔截
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                // mFirstTouchTarget != null這個意思是:ViewGroup本身不攔截事件世吨,而是把事件傳給子View處理了。
                // 也就是說呻征,一旦ViewGroup本身對事件進行了攔截處理耘婚,那么mFirstTouchTarget = null
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                // FLAG_DISALLOW_INTERCEPT:requestDisallowInterceptTouchEvent()中設置
                if (!disallowIntercept) {// 允許對事件進行攔截處理
                    intercepted = onInterceptTouchEvent(ev);// 
                    ev.setAction(action); // restore action in case it was changed
                } else {// 不允許對事件攔截
                    intercepted = false;
                }
            } else {// 如果ViewGroup本身對事件進行了處理,那么ACTION_MOVE,ACTION_UP等事件就直接被ViewGroup攔截了陆赋,不會再傳給子View了
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                intercepted = true;
            }
            // 以上部分總結(jié)一下:當接收到ACTION_DOWN事件的時候沐祷,會把一些東西清空和重置
            
            // 對于一次觸摸會產(chǎn)生一個事件序列,如果接收到action_down事件或者事件交給了子View來處理攒岛,
            // 在允許對事件進行攔截的情況下赖临,ViewGroup的onInterceptTouchEvent()會被執(zhí)行到并且只會執(zhí)行到一次(ACTION_DOWN事件)。
// 所以這里要注意一點灾锯,如果ViewGroup本身對ACTION_DOWN事件進行了攔截兢榨,
// 那么對于ACTION_MOVE,ACTION_UP等事件,因為mFirstTouchTarget != null為false挠进,
// actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null則返回false色乾,
// 那么intercepted一直為true,因而這些事件是不會再傳給子view的领突。
            
            // 從這里可以看到:
            // 如果ViewGroup本身對事件進行了處理暖璧,mFirstTouchTarget != null為false,那么onInterceptTouchEvent()只會被執(zhí)行一次,
            // 后續(xù)事件ACTION_MOVE,ACTION_UP等都不會進入 onInterceptTouchEvent()君旦;
            // 而如果ViewGroup本事沒有對事件進行處理澎办,而是交給了子View來處理蔑歌,
            // 那么mFirstTouchTarget != null為true手蝎,則事件序列中的每個事件都會進入onInterceptTouchEvent()
            // 驗證測試3.3結(jié)果
            

            // 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) {
                // ViewGroup本身對事件進行了攔截
                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) {
                // 事件沒有取消也沒有被ViewGroup本身攔截:事件分發(fā)給子View

                // 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.
                        // 對子view進行排序處理,最上層到最下層
                        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;
                            }

                            // 子View不可見沒有播放動畫碎紊,或者觸摸點不在子view上
                            if (!canViewReceivePointerEvents(child)// 子view既不可見或也沒有播放動畫
                                    || !isTransformedTouchPointInView(x, y, child, null)) {// 觸摸點在子view外
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                                
                            }

                            // 子View正在接收touch事件
                            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;
                            }
                            // 到這里newTouchTarget還是為null的
                            resetCancelNextUpFlag(child);
                            // 事件交由子view來處理了恕稠,這里的child是不為null的
                            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 被賦值琅绅,驗證了mFirstTouchTarget!=null表示事件交由子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();
                    }

                    // 事件交由子View來處理,但是卻沒有找到這樣的子view
                    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.
// 這里的child為null鹅巍,因而直接執(zhí)行view的dispatchTouchEvent()方法千扶,對事件進行處理料祠,不再傳給子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;
    }
4.8 ViewGroup.dispatchTransformedTouchEvent()
/**
     * Transforms a motion event into the coordinate space of a particular child view,
     * filters out irrelevant pointer ids, and overrides its action if necessary.
     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
     */
    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) {// 子View不存在,則交給ViewGroup的父類View來處理了
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {//子View存在
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }
            // 子view dispatchTouchEvent()
            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }
4.8 ViewGroup.addTouchTarget()
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
// mFirstTouchTarget 賦值了
        mFirstTouchTarget = target;
        return target;
    }
4.9 View.dispatchTouchEvent()
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)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            // 優(yōu)先執(zhí)行OnTouchListener.onTouch()
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            // 在OnTouchListener為null時才執(zhí)行onTouchEvent
           // 在onTouchEvent()中的ACTION_UP事件中判斷ClickListener是否不為null澎羞,
// 如果 不為null髓绽,則執(zhí)行onClick()
            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事件分發(fā)機制的基本過程妆绞,總得來說顺呕,當設備接收到事件的時候,先由activity來進行分發(fā)(dispatchTouchEvent())給window括饶,window接收到事件的時候交給DecorView來處理株茶,而DecorView本身是一個ViewGroup,因而存在自己攔截處理或是分發(fā)給子view來處理等幾種情況图焰,如果自己進行攔截處理(OnInterceptTouchEvent() return true),那么事件最終是否消費取決于ViewGroup.onTouchEvent()忌卤,并且事件是不會再傳給子View的;如果事件交由子view來處理楞泼,那么事件是否消費則由子view來定了,這個邏輯基本和現(xiàn)有邏輯一致笤闯。view對于事件的處理堕阔,是直接由onTouchEvent來決定的,在View.onTouchEvent()中首先會判斷是否有TouchListener颗味,如果有超陆,則直接執(zhí)行onTouch,如果沒有浦马,則再看clickListener有沒有时呀,有,執(zhí)行onClick晶默。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谨娜,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子磺陡,更是在濱河造成了極大的恐慌趴梢,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件币他,死亡現(xiàn)場離奇詭異坞靶,居然都是意外死亡,警方通過查閱死者的電腦和手機蝴悉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進店門彰阴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人拍冠,你說我怎么就攤上這事尿这〈氐郑” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵妻味,是天一觀的道長正压。 經(jīng)常有香客問我,道長责球,這世上最難降的妖魔是什么焦履? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮雏逾,結(jié)果婚禮上嘉裤,老公的妹妹穿的比我還像新娘。我一直安慰自己栖博,他們只是感情好屑宠,可當我...
    茶點故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著仇让,像睡著了一般典奉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上丧叽,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天卫玖,我揣著相機與錄音,去河邊找鬼踊淳。 笑死假瞬,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的迂尝。 我是一名探鬼主播脱茉,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼垄开!你這毒婦竟也來了琴许?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤说榆,失蹤者是張志新(化名)和其女友劉穎虚吟,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體签财,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡串慰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了唱蒸。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片邦鲫。...
    茶點故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出庆捺,到底是詐尸還是另有隱情古今,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布滔以,位于F島的核電站捉腥,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏你画。R本人自食惡果不足惜抵碟,卻給世界環(huán)境...
    茶點故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望坏匪。 院中可真熱鬧拟逮,春花似錦、人聲如沸适滓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽凭迹。三九已至罚屋,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間嗅绸,已是汗流浹背沿后。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留朽砰,地道東北人。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓喉刘,卻偏偏與公主長得像瞧柔,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子睦裳,可洞房花燭夜當晚...
    茶點故事閱讀 44,779評論 2 354

推薦閱讀更多精彩內(nèi)容