Android 利用源码调试 详解TouchEvent 事件分发机制

1.如果有触摸事件,首先会调用到Activity 的dispatchTouchEvent 方法。

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

getWindow().superDispatchTouchEvent 最终会调用PhoneWindow 的 superDispatchTouchEvent

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

mDecor.superDispatchTouchEvent(event); 最终会调用到DecorView 类的 dispatchTouchEvent

2.然后我们来看DecorView.dispatchTouchEvent 是怎么写的。

因为DecorView 是 FrameLayout 的子类,所以,他的dispatchTouchEvent 代码在ViewGroup 类的dispatchTouchEvent (FrameLayout 里面是没有dispatchTouchEvent 这个方法的,所以在ViewGroup 里面),如下:

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    	
    	****************
        boolean handled = false;
        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.
                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 accessibility 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 = 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();
                    }

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

可能这个方法有点长,有点复杂,但是看懂这一段,就可以完全理解TouchEvent 事件传递机制。

3. dispatchTouchEvent 里面会去检查,当前的ViewGroup 是不是拦截 拦截事件

如果是的话,就不会遍历每个子View,也就是不会把事件传递给下一级。

            // 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 (!canceled && !intercepted) {           
                 // 不拦截才回去走具体的分发给子view 的 touchEvent     
            }

在这里面回到用onInterceptTouchEvent,但是不是所有的情况都会调用。是有判断的。如果当前是ActionDown,或者mFirstTouchTarget 不是空,那么再去判断有没有子View 调用过getParent().requestDisallowInterceptTouchEvent(true); 如果有子View 请求不要拦截,那么就不会再走onInterceptTouchEvent,否则还是会走onInterceptTouchevent.

4.如果不拦截就会走到这里:

		if (!canceled && !intercepted) {
                
                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        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);
                             // 如果当前事件的位置,不在子view 里面,那么就continue      
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            //子view 再去分发给他的子view
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {            
                            // 走到这里表示子view 是要处理的               
                                // 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;
                                }
                                // 把要处理的view 加到mFirstTouchTarget 字段里
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                        }
                    }

    /**
     * Adds a touch target for specified child to the beginning of the list.
     * Assumes the target child is not already present.
     */
    private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

这里面会调用dispatchTransformedTouchEvent 方法。

4.dispatchTransformedTouchEvent 这个方法是个很重要的方法。

我们来看下他有一个参数是View child ,如果传递的参数的child 不是空,就会调用dispatchTouchEvent,继续往下传递。如果child是空只能说明一个问题,已经遍历到view 的最后一级了,已经没有子View 了。这时候就会调用super.dispatchTouchEvent方法. 调用super.dispatchTouchEvent 就会调用View 类的onTouchEvent。因为ViewGroup 也好,TextView 等也要,都是View 的子类。


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

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

View 类的dispatchTouchEvent。他会调用onTouchEvent,如下:


    /**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        
        boolean result = false;

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

5.如果某一个view dispatchTouchEvent 或者onTouch 返回了true, 那么就会把这个View 记录在当前ViewGroup 的mFirstTouchTarget 字段里面。

以后每次分发Action Move, Action up 都不会再去遍历查找要处理Touch事件的View. 直接使用mFirstTouchTarget.

					if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {                             
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                       }

6.如果最底层的view 的onTouchEvent依然不处理,那么就不会记录到mFirstTouchTarget 字段里面。

然后方法会继续执行到dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);,因为这里的child 传递的是null,所以会调用onTouchEvent.
如果也不处理,代码会继续走到父View 的onTouchEvent, 看看处理不处理。

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

如果都不处理,那么最后会执行到Activity 的 onTouchEvent,如下:

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

具体流程:

收到ACTION_DOWN 事件的时候

首先执行最外层ViewGroup 的dispatchTouchEvent,然后执行onInterceptTouchEvent,看看自己拦截不拦截,如果拦截,直接执行当前ViewGroup 的OnTouchEvent,看看自己处理不处理,并把结果返回给Parent.
如果不拦截,遍历循环子View,如果子veiw 是 ViewGroup 类型的,那么调用子View 的dispatchTouchEvent, 继续调用子View 的 onInterceptTouchEvent,如果拦截,就直接执行当前ViewGroup的OnTouchEvent。并把结果返给Parent. ,如果不拦截的话,如果这个ViewGroup 还有子view,那么就继续往下传递。如果子View 是View类型,在dispatchTouchEvent 里面 会首先判断当前View 有没有设置onTouchListener,如果有那么看一下
onTouchListener 返回true 还是false,如果返回true 表示这个onTouchListener要处理事件,否则的话,表示不处理。就会继续走View 的onTouchEvent 方法。
直至view 树的最后一个View,如果最后这个view dispatchTouchEvent onTouchEvent 都不返回true 的话,(不处理的),然后就开始返回到parent。执行到父view 的 dispatchTouchEvent方法里面, 因为子View 不处理,mFirstTouchTarget 就是空的,所以会调用到父View 的 onTouchEvent,看看父View 处理不处理,有些ViewGroup 是自己处理TouchEvent的,比如ScrollView. 可以看到ScrollView 的onTouchEvent 方法恒返回true. 如果父View 的onTouchEvent也不处理,就执行父父View dispatchTouchEvent, 以此类推。
最后都不执行,就执行Activity 的OnTouchEvent.

当收到ACTION_MOVE 事件的时候

ViewGroup 会判断mFirstTouchTarget 是不是空,如果是空表示没有人处理这次的点击事件,那么就不再调用onInterceptTouchEvent,直接调用自己的onTouchEvent.
如果当前ViewGroup 的mFirstTouchTarget 不是空,首先判断一下子View 有没有调用过getParent().requestDisallowInterceptTouchEvent(true); 如果没有子View 调用过这个方法,那么会走onInterceptTouchEvent方法,看一下自己是不是拦截,如果自己拦截,那么就发送Action_Cancle 给mFirstTouchEvent。然后自己处理剩下的事件,比如ScrollView.如果自己的onInterceptTouchEvent 不拦截,那么把事件传递给mFirestTouchTarget 处理。如果mFirestTouchTarget 表示,ACTION_MOVE,我也不处理,但是整个调用链上没有任何parent 拦截的话,之后的ACTION_MOVE 还是会发送给mFirestTouchTarget 处理。

当收到Action_Up 的时候

如果ViewGroup 的mFirstTouchTarget 是不是空,如果是空,那么调用自己的onTouchEvent.如果ViewGroup 的mFirstTouchTarget 不是空的话,就会走当前ViewGroup 的onInterceptTouchEvent,看一下自己不是拦截,如果拦截,那么就发送Action_Cancle 给mFirstTouchTarget.mFirestTouchTarget 又会用用样的方式,传递给他的mFirestTouchTarget.直到完成。

1.ACTION_DOWN ViewGroup 寻找哪个子View来处理这个事件,找到了放到mFirstTouchTarget里面。形成一条调用链。
2.ACTION_MOVE 的时候,如果子view 没有调用requestDisallowInterecptTouchEvent,那么继续走ViewGroup的onInterceptToucheEvent.看看自己拦不拦截。如果不拦截,那么看看mFirstTouchTarget 是不是空,如果不是空,那么传递给mFirstTouchTarge,否则调用自己的onTouchEvent。这一步不再进行分发,如果你想要在move 的时候继续判断用户手势上下决定要不要处理事件,那么你就要在ActionDown的时候,就要返回True,你才能接受之后的事件,当你判断用户手势自己要处理的时候,那么调用requestDisallowInterecptTouchEvent,告诉父亲都不要拦截我的事件了。
3.如果这时候ViewGroup拦截了,那么分发cancle给mFristTouchTarget。否则的话,就按正常的调用链传递

总结:

1.下载aosp 调试之后,才永远都了解事件传递机制。否则的话,只能看别人说,也看不懂源码,最终面试都会忘记。
2.下载了源码,可以调试就是爽。加油吧。为了我的媳妇。

资料:

以下为调用堆栈截图:
可以看到会循环view 调用dispatchTouchEvent
在这里插入图片描述
调用具体堆栈:

	  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2679)
	  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3048)
	  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2677)
	  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3048)
	  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2677)
	  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3048)
	  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2677)
	  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3048)
	  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2677)
	  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3048)
	  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2677)
	  at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:440)
	  at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1830)
	  at android.app.Activity.dispatchTouchEvent(Activity.java:3437)
	  at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:69)
	  at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:398)
	  at android.view.View.dispatchPointerEvent(View.java:12833)
	  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5146)
	  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4949)
	  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4452)
	  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4505)
	  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4471)
	  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4611)
	  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4479)
	  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4668)
	  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4452)
	  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4505)
	  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4471)
	  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4479)
	  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4452)
	  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7143)
	  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7112)
	  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7073)
	  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7246)
	  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:189)
	  at android.os.MessageQueue.nativePollOnce(MessageQueue.java:-1)
	  at android.os.MessageQueue.next(MessageQueue.java:326)
	  at android.os.Looper.loop(Looper.java:160)
	  at android.app.ActivityThread.main(ActivityThread.java:6743)
	  at java.lang.reflect.Method.invoke(Method.java:-1)
	  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
	  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:882)

问:如果已经有View 表示处理touchEvent,那么onInterceptTouchEvent 还会调用吗?

会!

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

上面这段代码,如果event 已经有view 处理,那么mFirstTouchTarget 就不会null,那么就会走onInterceptTouchEvent。所以,就算当时已经有view处理,如果没有调用getParent().requestDisallowInterceptTouchEvent(true); 还是可以拦截的。

如何打印mFirstTouchTarget ?

        Object mFirstTouchTarget = Util.getField(this, "mFirstTouchTarget");

        Log.e("ViewShelfHeadParent= onInterceptTouchEvent ", mFirstTouchTarget != null ?  Util.getField(mFirstTouchTarget, "child").getClass().getSimpleName():"null");

为什么我的View onInterceptTouchEvent 只走了一次?

如果发生了onTouchDown,在传递链中的一个的View返回了true,在这个传递链往后的View onTouchEvent 都没有返回true.那么之后的move事件,从这个View 往后都不会在收到。dispatchTouchEvent 也不会再走。onInterceptTouchEvent.同样因为后面的分发就不会再走你了。因为你既不是ACTION_DOWN,mFirstTouchTarget 又是null.那么之后,你的父View你根本不再传递链里面。

View 的 mOnTouchListener先调用 还是onTouchEvent 先调用?

肯定是mOnTouchListener 先调用,如果mOnTouchListener 不处理才调用自己的onTouchEvent 的。不然mOnTouchListener 什么时候处理? ouTouchEvent 处理完再处理?那你设置Listener 还有啥用?
具体代码是:android.view.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)) {
            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;
            }
        }

怎么处理滑动冲突?

在父容器的onInterceptTouchEvent 里面,判断action_move 的时候,父容器处不处理,如果处理,那么就返回true,拦截时间,否则返回false 就行了。
如果你在返回true 的时候,记得调用parent.requestDisallowInterceptTouchEvent 这是一个好习惯。

当然你也可以在子view 里面处理。不建议在子view 里面处理,因为父view 一个地方就可以处理,子view处理的话,父view 还是要判断什么情况自己处理。

可以去看下ListView,ScrollView 等,都是只在onInterceptTouchEvent 处理,简单清晰。

参考:https://www.bbsmax.com/A/1O5E9ZYn57/

View 的OnClickListener 是怎么执行的?

如果一个view的onTouchEvent 返回true. 在ACTION_DOWN的时候,会postDelayed 一个 Runnable,用来检测 是不是长按事件。然后在ACTION_UP的时候,去判断一下,这个mOnLongClickListener 是不是执行了,如果执行了mOnLongClickListener ,那么说明是长按事件,就不再调用mOnClickListener。

(可以看View 的onTouch 方法,一般是clickable 的话,就直接返回true了),那么在Action_down 的时候,就会返回true

如果一个View 是disabled , 但是clickAble 是true ,他会消费事件吗?

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

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

会的,看下面代码:

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }

如果试试disable 的,但是你clickable 的话,那么这个view 还是会消费事件,不过不会真的调用View 的具体的onTouch

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页