android事件分發(fā)機(jī)制

android中的事件處理,以及解決滑動沖突問題都離不開事件分發(fā)機(jī)制砖第,android中的事件流荷腊,即MotionEvent都會經(jīng)歷一個(gè)從分發(fā),攔截到處理的一個(gè)過程悄窃。即dispatchTouchEvent(),onInterceptEvent()到onTouchEvent()的一個(gè)過程讥电,在dispatchTouchEvent()負(fù)責(zé)了事件的分發(fā)過程,在dispatchTouchEvent()中會調(diào)用onInterceptEvent()與onTouchEvent()轧抗,如果onInterceptEvent()返回true恩敌,那么會調(diào)用到當(dāng)前view的onTouchEvent()方法,如果不攔截横媚,事件就會下發(fā)到子view的dispatchTouchEvent()中進(jìn)行同樣的操作纠炮。本文將帶領(lǐng)大家從源碼角度來分析android是如何進(jìn)行事件分發(fā)的月趟。

android中的事件分發(fā)流程最先從activity的dispatchTouchEvent()開始:

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

這里調(diào)用了getWindow().superDispatchTouchEvent(ev),這里可以看出activity將MotionEvent傳寄給了Window恢口。而Window是一個(gè)抽象類狮斗,superDispatchTouchEvent()也是一個(gè)抽象方法,這里用到的是window的子類phoneWindow弧蝇。

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

從這里可以看出碳褒,event事件被傳到了DecorView,也就是我們的頂層view.我們繼續(xù)跟蹤:

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

這里調(diào)用到了父類的dispatchTouchEvent()方法,而DecorView是繼承自FrameLayout看疗,F(xiàn)rameLayout繼承了ViewGroup,所以這里會調(diào)用到ViewGroup的dispatchTouchEvent()方法沙峻。

所以整個(gè)事件流從activity開始,傳遞到window两芳,最后再到我們的view(viewGroup也是繼承自view)中摔寨,而view才是我們整個(gè)事件處理的核心階段。

我們來看一下viewGroup的dispatchTouchEvent()中的實(shí)現(xiàn):

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

這是dispatchTouchEvent()開始時(shí)截取的一段代碼怖辆,我們來看一下是复,首先,當(dāng)我們手指按下view時(shí)竖螃,會調(diào)用到resetTouchState()方法淑廊,在resetTouchState()中:

private void resetTouchState() {
    clearTouchTargets();
    resetCancelNextUpFlag(this);
    mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
    mNestedScrollAxes = SCROLL_AXIS_NONE;
}

我們繼續(xù)跟蹤clearTouchTargets()方法:

private void clearTouchTargets() {
    TouchTarget target = mFirstTouchTarget;
    if (target != null) {
        do {
            TouchTarget next = target.next;
            target.recycle();
            target = next;
        } while (target != null);
        mFirstTouchTarget = null;
    }
}

在clearTouchTargets()方法中,我們最終將mFirstTouchTarget賦值為null特咆,我們繼續(xù)回到dispatchTouchEvent()中季惩,接著執(zhí)行了下段代碼:

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

當(dāng)view被按下或mFirstTouchTarget != null 的時(shí)候看靠,從前面可以知道洁奈,當(dāng)每次view被按下時(shí),也就是重新開始一次事件流的處理時(shí)夺谁,mFirstTouchTarget都會被設(shè)置成null菜职,一會我們看mFirstTouchTarget是什么時(shí)候被賦值的青抛。
從disallowIntercept屬性我們大概能猜到是用來判斷是否需要坐攔截處理,而我們知道可以通過調(diào)用父view的requestDisallowInterceptTouchEvent(true)可以讓我們的父view不能對事件進(jìn)行攔截酬核,我們先來看看requestDisallowInterceptTouchEvent()方法中的實(shí)現(xiàn):

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

這里也是通過設(shè)置標(biāo)志位做判斷處理蜜另,所以這里是通過改變mGroupFlags標(biāo)志,然后在dispatchTouchEvent()剛發(fā)中變更disallowIntercept的值判斷是否攔截愁茁,當(dāng)為true時(shí)蚕钦,即需要攔截,這個(gè)時(shí)候便會跳過onInterceptTouchEvent()攔截判斷鹅很,并標(biāo)記為不攔截嘶居,即intercepted = false,我們繼續(xù)看viewGroup的onInterceptTouchEvent()處理:

public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
            && ev.getAction() == MotionEvent.ACTION_DOWN
            && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
            && isOnScrollbarThumb(ev.getX(), ev.getY())) {
        return true;
    }
    return false;
}

即默認(rèn)情況下,只有在ACTION_DOWN時(shí)邮屁,viewGroup才會表現(xiàn)為攔截整袁。

我們繼續(xù)往下看:

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 = buildTouchDispatchChildList();
      final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
      final View[] children = mChildren;
      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);
                        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();
                }

這段代碼首先會通過一個(gè)循環(huán)去遍歷所有的子view,最終會調(diào)用到dispatchTransformedTouchEvent()方法佑吝,我們繼續(xù)看dispatchTransformedTouchEvent()的實(shí)現(xiàn):

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,始終會調(diào)用到child.dispatchTouchEvent();否則調(diào)用super.dispatchTouchEvent();

如果child不為null時(shí)芋忿,事件就會向下傳遞炸客,如果子view處理了事件,即dispatchTransformedTouchEvent()即返回true戈钢。繼續(xù)向下執(zhí)行到addTouchTarget()方法痹仙,我們繼續(xù)看addTouchTarget()方法的執(zhí)行結(jié)果:

private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
    final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}

這個(gè)時(shí)候我們發(fā)現(xiàn)mFirstTouchTarget又出現(xiàn)了,這時(shí)候會給mFirstTouchTarget重新賦值殉了,即mFirstTouchTarget不為null开仰。也就是說,如果事件被當(dāng)前view或子view消費(fèi)了薪铜,那么在接下來的ACTION_MOVE或ACTION_UP事件中众弓,mFirstTouchTarget就不為null。但如果我們繼承了該viewGroup隔箍,并在onInterceptTouchEvent()的ACTION_MOVE中攔截了事件谓娃,那么后續(xù)事件將不會下發(fā),將由該viewGroup直接處理鞍恢,從下面代碼我們可以得到:

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

當(dāng)存在子view并且事件被子view消費(fèi)時(shí)傻粘,即在ACTION_DOWN階段mFirstTouchTarget會被賦值,即在接下來的ACTION_MOVE事件中帮掉,由于intercepted為true,所以將ACTION_CANCEL 事件傳遞過去窒典,從dispatchTransformedTouchEvent()中可以看到:

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

并將mFirstTouchTarget 最終賦值為 next蟆炊,而此時(shí)mFirstTouchTarget位于TouchTarget鏈表尾部,所以mFirstTouchTarget會賦值為null瀑志,那么接下來的事件將不會進(jìn)入到onInterceptTouchEvent()中涩搓。也就會直接交由該view處理。

如果我們沒有進(jìn)行事件的攔截劈猪,而是交由子view去處理昧甘,由于ViewGroup的onInterceptTouchEvent()默認(rèn)并不會攔截除了ACTION_DOWN以外的事件,所以后續(xù)事件將繼續(xù)交由子view去處理战得,如果存在子view且事件位于子view內(nèi)部區(qū)域的話充边。

所以無論是否進(jìn)行攔截,事件流都會交由view的dispatchTouchEvent()中進(jìn)行處理,我們接下來跟蹤一下view中的dispatchTouchEvent()處理過程:

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

    if (onFilterTouchEventForSecurity(event)) {
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        //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;
        }
    }

當(dāng)被按下時(shí)浇冰,即ACTION_DOWN時(shí)贬媒,view會停止內(nèi)部的滾動,如果view沒有被覆蓋或遮擋時(shí)肘习,首先會進(jìn)行mListenerInfo是否為空的判斷际乘,我們看下mListenerInfo是在哪里初始化的:

ListenerInfo getListenerInfo() {
    if (mListenerInfo != null) {
        return mListenerInfo;
    }
    mListenerInfo = new ListenerInfo();
    return mListenerInfo;
}

這里可以看出,mListenerInfo一般不會是null漂佩,知道在我們使用它時(shí)調(diào)用過這段代碼脖含,而當(dāng)view被加入window中的時(shí)候,會調(diào)用下面這段代碼投蝉,從注釋中也可以看出來:

/**
 * Add a listener for attach state changes.
 *
 * This listener will be called whenever this view is attached or detached
 * from a window. Remove the listener using
 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
 *
 * @param listener Listener to attach
 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
 */
public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
    ListenerInfo li = getListenerInfo();
    if (li.mOnAttachStateChangeListeners == null) {
        li.mOnAttachStateChangeListeners
                = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
    }
    li.mOnAttachStateChangeListeners.add(listener);
}

到這里我們就知道养葵,mListenerInfo一開始就是被初始化好了的,所以li不可能為null墓拜,li.mOnTouchListener != null即當(dāng)設(shè)置了TouchListener時(shí)不為null港柜,并且view是enabled狀態(tài),一般情況view都是enable的咳榜。這個(gè)時(shí)候會調(diào)用到onTouch()事件夏醉,當(dāng)onTouch()返回true時(shí),這個(gè)時(shí)候result會賦值true涌韩。而當(dāng)result為true時(shí)畔柔,onTouchEvent()將不會被調(diào)用。

從這里可以看出臣樱,onTouch()會優(yōu)先onTouchEvent()調(diào)用靶擦;
當(dāng)view設(shè)置touch監(jiān)聽并返回true時(shí),那么它的onTouchEvent()將被屏蔽雇毫。否則會調(diào)用onTouchEvent()處理玄捕。

那么讓我們繼續(xù)來看看onTouchEvent()中的事件處理:

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

首先,當(dāng)view狀態(tài)是DISABLED時(shí)棚放,只要view是CLICKABLE或LONG_CLICKABLE或CONTEXT_CLICKABLE枚粘,都會返回true,而button默認(rèn)是CLICKABLE的,textview默認(rèn)不是CLICKABLE的飘蚯,而view一般默認(rèn)都不是LONG_CLICKABLE的馍迄。

我們繼續(xù)向下看:

if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }

如果有代理事件,仍然會返回true.

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)) {
                                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, x, y);
                }
                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;
    }

當(dāng)view是CLICKABLE或LONG_CLICKABLE或CONTEXT_CLICKABLE狀態(tài)時(shí)局骤,當(dāng)手指抬起時(shí)攀圈,如果設(shè)置了click監(jiān)聽,最終會調(diào)用到performClick()峦甩,觸發(fā)click()事件赘来。這點(diǎn)從performClick()方法中可以看出:

public boolean performClick() {
    final boolean result;
    final ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnClickListener != null) {
        playSoundEffect(SoundEffectConstants.CLICK);
        li.mOnClickListener.onClick(this);
        result = true;
    } else {
        result = false;
    }

    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
    return result;
}

從這里我們也可以得出,click事件會在onTouchEvent()中被調(diào)用,如果view設(shè)置了onTouch()監(jiān)聽并返回true撕捍,那么click事件也會被屏蔽掉拿穴,不過我們可以在onTouch()中通過調(diào)用view的performClick()繼續(xù)執(zhí)行click()事件,這個(gè)就看我們的業(yè)務(wù)中的需求了忧风。

從這里我們可以看出默色,如果事件沒有被當(dāng)前view或子view處理,即返回false狮腿,那么事件就會交由外層view繼續(xù)處理腿宰,直到被消費(fèi)。

如果事件一直沒有被處理缘厢,會最終傳遞到Activity的onTouchEvent()中吃度。

到這里我們總結(jié)一下:
事件是從Activity->Window->View(ViewGroup)的一個(gè)傳遞流程;

如果事件沒有被中途攔截贴硫,那么它會一直傳到最內(nèi)層的view控件椿每;

如果事件被某一層攔截,那么事件將不會向下傳遞英遭,交由該view處理间护。如果該view消費(fèi)了事件,那么接下來的事件也會交由該view處理挖诸;如果該view沒有消費(fèi)該事件汁尺,那么事件會交由外層view處理,...并最終調(diào)用到activity的onTouchEvent()中多律,除非某一層消費(fèi)了該事件痴突;

一個(gè)事件只能交由一個(gè)view處理;

DispatchTouchEvent()總是會被調(diào)用狼荞,而且最先被調(diào)用辽装,onInterceptTouchEvent()和onTouchEvent()在DispatchTouchEvent()內(nèi)部調(diào)用;

子view不能干擾ViewGroup對ACTION_DOWN事件的處理相味;

子view可以通過requestDisallowInterceptTouchEvent(true)控制父view不對事件進(jìn)行攔截如迟,跳過onInterceptTouchEvent()方法的執(zhí)行。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末攻走,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子此再,更是在濱河造成了極大的恐慌昔搂,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件输拇,死亡現(xiàn)場離奇詭異摘符,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門逛裤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瘩绒,“玉大人,你說我怎么就攤上這事带族∷螅” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵蝙砌,是天一觀的道長阳堕。 經(jīng)常有香客問我,道長择克,這世上最難降的妖魔是什么恬总? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮肚邢,結(jié)果婚禮上壹堰,老公的妹妹穿的比我還像新娘。我一直安慰自己骡湖,他們只是感情好贱纠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著勺鸦,像睡著了一般并巍。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上换途,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天懊渡,我揣著相機(jī)與錄音,去河邊找鬼军拟。 笑死剃执,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的懈息。 我是一名探鬼主播肾档,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼辫继!你這毒婦竟也來了怒见?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤姑宽,失蹤者是張志新(化名)和其女友劉穎遣耍,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體炮车,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡舵变,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年酣溃,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片纪隙。...
    茶點(diǎn)故事閱讀 39,919評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡赊豌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出绵咱,到底是詐尸還是另有隱情碘饼,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布麸拄,位于F島的核電站派昧,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏拢切。R本人自食惡果不足惜蒂萎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望淮椰。 院中可真熱鬧五慈,春花似錦、人聲如沸主穗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽忽媒。三九已至争拐,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間晦雨,已是汗流浹背架曹。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留闹瞧,地道東北人绑雄。 一個(gè)月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像奥邮,于是被迫代替她去往敵國和親万牺。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評論 2 354

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