Android Touch事件分发

Android 中的Touch事件是由最上层的DecorView进行分发的。

当一个Touch事件产生的时候,先会执行事件的分发,分发的过程是:Activity —>    DecorView —> ViewGroup —>ViewGroup —> TargetView

执行的方法有dispatchTouchEvent()和onInterceptedTouchEvent()这两个方法。

在消耗Touch事件的时候,执行的过程正好是产生Touch事件的反向过程,消耗的过程是:TargetView —> ViewGroup —>ViewGroup —>DecorView —>Activity 执行的方法有 onTouchEvent()。

 

在Touch进行执行的过程中执行的方法有

1⃣️dispatchTouchEvent()

2⃣️onInterceptedTouchEvent()

3⃣️onTouchEvent()

第一个方法与第二个方法是用与事件分发的,第一个是进行事件传递返回ture的时候事件可以进行向下传递,但是还需要进行是否拦截的判断也就是需要执行一下onInterceptedTouchEvent()这个方法,这个方法用于判断是不是对当前传递的Touch事件进行拦截返回ture那么就会对当前传递的事件进行拦截,那么就不会将事件传递下面的View和ViewGroup,返回false的话会将Touch事件继续传递下去知道找到了目标的View 或者没有View处理这个Touch事件。

第三个方法是处理Touch事件的方法 如果找到TargetView的话 这个TargetView会处理Touch事件并且返回true通知顶层的DecorView记录处理这个Touch事件的View。同时与onTouchEvent方法类似的方法还有三个:onTouch onClick onLongClick 这四个方法的执行顺序为 onTouch --> onTouchEvent —>onClick —>

onLongClick。

说了一堆还是先看看源码分别看看ViewGroup以及View中的dispatchTouchEvent

ViewGroup:

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

        if (onFilterTouchEventForSecurity(ev)) {

            final int action = ev.getAction();

            final int actionMasked = action & MotionEvent.ACTION_MASK;

 

            // Handle an initial down.处理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 = 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;

    }

 上面的代码就是ViewGroup中的dispatchTouchEvent的源码,这个源码中能看出在ViewGroup里面只负责分发Touch事件并且记录是由那个View处理的Touch事件。

下面来看看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;

        if (li != null && li.mOnTouchListener != null

                && (mViewFlags & ENABLED_MASK) == ENABLED

                && li.mOnTouchListener.onTouch(this, 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;

}

通过上面的代码我们可以看到View中的dispatchTouchEvent方法只负责处理这个Touch事件到底是由那个方法进行处理,上面的红色部分可以看出先去寻着有没有Linsenter没有的话交由onTouchEvent方法进行处理,而onTouchEvent方法中会掉油performClick方法出发onClick方法。

 

没有控件消耗这个事件的时候Touch执行过程中每个方法的值:

08-09 10:09:23.197 32646-32646/com.example.zengfanrui.practice E/TouchTestViewGroup: onInterceptTouchEvent    false     ev.action0    0

08-09 10:09:23.197 32646-32646/com.example.zengfanrui.practice E/TouchTestView: onTouchEvent    falseevent.action0

    dispatchTouchEvent    falseevent.action0

08-09 10:09:23.197 32646-32646/com.example.zengfanrui.practice E/TouchTestViewGroup: dispatchTouchEvent    false     ev.action0    0

有控件消耗这个事件的时候Touch执行过程中每个方法的值:

08-09 10:11:42.496 2357-2357/com.example.zengfanrui.practice E/TouchTestViewGroup: onInterceptTouchEvent    false     ev.action0    0

08-09 10:11:42.497 2357-2357/com.example.zengfanrui.practice E/TouchTestView: onTouchEvent    trueevent.action0

    dispatchTouchEvent    trueevent.action0

08-09 10:11:42.497 2357-2357/com.example.zengfanrui.practice E/TouchTestViewGroup: dispatchTouchEvent    true     ev.action0    0

08-09 10:11:42.618 2357-2357/com.example.zengfanrui.practice E/TouchTestViewGroup: onInterceptTouchEvent    false     ev.action1    1

08-09 10:11:42.618 2357-2357/com.example.zengfanrui.practice E/TouchTestView: onTouchEvent    trueevent.action1

    dispatchTouchEvent    trueevent.action1

08-09 10:11:42.618 2357-2357/com.example.zengfanrui.practice E/TouchTestViewGroup: dispatchTouchEvent    true     ev.action1    1

主要是ViewGroup中的dispatchTouchEvent方法中调用父类方法的返回值不同,没有控件消耗的时候是false有控件消耗的时候返回的是true。

如果在ViewGroup dispatchTouchEvent方法可以设置true 那么无论有没有控件处理Touch事件都会将事件进行下发,

08-09 10:14:22.043 4429-4429/com.example.zengfanrui.practice E/TouchTestViewGroup: onInterceptTouchEvent    false     ev.action0    0

08-09 10:14:22.043 4429-4429/com.example.zengfanrui.practice E/TouchTestView: onTouchEvent    falseevent.action0

    dispatchTouchEvent    falseevent.action0

08-09 10:14:22.043 4429-4429/com.example.zengfanrui.practice E/TouchTestViewGroup: dispatchTouchEvent    true     ev.action0    0

08-09 10:14:22.157 4429-4429/com.example.zengfanrui.practice E/TouchTestViewGroup: dispatchTouchEvent    true     ev.action1    1

通过上面的日志中可以看出如果设置返回值为true之后 没有控件处理事件的时候也一样会将除去down事件的其他事件分发下去。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值