Android-ViewGoup事件分发机制

前言

Android的事件分发机制是从上往下进行分发,了解了View的事件分发后,我们还需要了解ViewGroup的事件分发原理。实际中View是和ViewGroup结合使用的,同时这两者之间还存在嵌套滑动。

ViewGoup事件分发源码解析

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        .......
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
            //对ACTION_DOWN进行初始处理
            // 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 isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
                    && !isMouseEvent;
            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 =
                                isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
                        final float y =
                                isMouseEvent ? ev.getYCursorPosition() : 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 (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                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()控制的,从贴出的该方法的代码来看,相对比较复杂;但是我们可以忽略一些代码,了解事件分发这块的流程即可,其他的可以放在后面研究。接下来我们一步一步的拆解其中的流程。

触摸事件进入dispatchTouchEvent()方法后,针对ACTION_DOWN先执行以下逻辑:当开始一个新的触摸手势时,放弃所有以前的状态;由于应用程序切换、ANR或其他状态更改,framework可能已经放弃了前一个手势的up或cancel事件。这块代码了解即可。

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

接下来判断ACTION_DOWN是否拦截:

// Check for interception.
//mFirstTouchTarget为触摸目标,初始为空
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
        || mFirstTouchTarget != null) {
    final boolean  // requestDisallowInterceptTouchEvent()  = (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;
}

上面的代码中 disallowIntercept,代码不做处理的情况下默认值是false,该值由mGroupFlags确定,其中mGroupFlags由requestDisallowInterceptTouchEvent() 进行修改,true表示不执行拦截方法。从上面的代码中,disallowIntercept为false的情况下,执行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;
}

检查完事件拦截后,如果不拦截事件,那么会将事件分发到childView中:

 //寻找新的触摸目标
 TouchTarget newTouchTarget = null;
 boolean alreadyDispatchedToNewTouchTarget = false;

 final int childrenCount = mChildrenCount;
 if (newTouchTarget == null && childrenCount != 0) {
    ......
    if (!canceled && !intercepted) {
    .....
    //寻找能够接收事件的child
    final ArrayList<View> preorderedList = buildTouchDispatchChildList();
    final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
    for (int i = childrenCount - 1; i >= 0; i--) {
            final int childIndex = getAndVerifyPreorderedIndex(
                    childrenCount, i, customOrder);
            final View child = getAndVerifyPreorderedView(
                    preorderedList, children, childIndex);
            if (!child.canReceivePointerEvents()
                    || !isTransformedTouchPointInView(x, y, child, null)) {
                continue;
            }
            newTouchTarget = getTouchTarget(child);
            //找到触摸目标View结束寻找
            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;
            }
            //这里将事件分发到childView处理,如果child消费事件,找到新的触摸view,结束寻找
            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                ......
                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                alreadyDispatchedToNewTouchTarget = true;
                break;
            }
            ......
            
     } 
     
     // Dispatch to touch targets.
    if (mFirstTouchTarget == null) {
        // 没有接触目标,所以将其视为普通视图。
        handled = dispatchTransformedTouchEvent(ev, canceled, null,
                TouchTarget.ALL_POINTER_IDS);
    } else {
        //分发到新的目标
        ......
    }
     
 }
 
 }

上面得代码片段中有个重要的方法dispatchTransformedTouchEvent(),主要是用于事件的分发处理,用于处理是调用child.dispatchTouchEvent还是super.dispatchTouchEvent()。ViewGroup继承View,所以自身的事件分发处理会使用View的dispatchToucheEvent()逻辑。

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

ViewGroup的dispatchTouchEvent()方法的实现较复杂,上述的分析已源码加文本说明为主,了解了其实现原理和流程后,ViewGroup的事件分发主要由以下特点:

  1. 事件传递dispatchTouchEvent(),会结合disallowIntercept方法进行判断是否执行onInterceptTouchEvent()方法。
  2. 如果onInterceptTouchEvent()拦截事件后,会调用super.dispatchToucheEvent()同时也就是View的dispatchToucheEvent()逻辑

了解MotionEvent中的action

在开发中,我们一般需要重写onIntercepTouchEvent()方法来完成我们的功能处理,这里就需要针对MotionEvent中不同的action进行不同的处理。我们通过下面的代码来测试onTntercepToucheEvnent对事件传递的影响。

public class MyLayout extends FrameLayout {

    public MyLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d("EventTag", "viewGroup_onInterceptTouchEvent:" + "ACTION_DOWN");
            return false;
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d("EventTag", "viewGroup_onInterceptTouchEvent:" + "ACTION_MOVE");
            return true;
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d("EventTag", "viewGroup_onInterceptTouchEvent:" + "ACTION_UP");
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d("EventTag", "viewGroup_onTouchEvent:" + "ACTION_DOWN");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d("EventTag", "viewGroup_onTouchEvent:" + "ACTION_MOVE");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d("EventTag", "viewGroup_onTouchEvent:" + "ACTION_UP");
        }
        return super.onTouchEvent(event);
    }
}

1,测试一:onInterceptTouchEvent的ACTION_DOWN返回ture,判断事件的传递过程

6720-6720/com.water.view.demo D/EventTag: viewGroup_onInterceptTouchEvent:ACTION_DOWN
6720-6720/com.water.view.demo D/EventTag: viewGroup_onTouchEvent:ACTION_DOWN

从上面的输出日志中可以看出,如果在onIntercepTouchEvent中拦截了ACTION_DOWN事件,事件不会传递到子View中.

2,测试二:onInterceptTouchEvent返回false,childView的onTouchEvent中消费ACTION_DOWN和ACTION_MOVE

8125-8125/com.water.view.demo D/EventTag: viewGroup_onInterceptTouchEvent:ACTION_DOWN
8125-8125/com.water.view.demo D/EventTag: childView_onTouchEvent:ACTION_DOWN
8125-8125/com.water.view.demo D/EventTag: viewGroup_onInterceptTouchEvent:ACTION_MOVE
8125-8125/com.water.view.demo D/EventTag: childView_onTouchEvent:ACTION_MOVE
8125-8125/com.water.view.demo D/EventTag: viewGroup_onInterceptTouchEvent:ACTION_UP
8125-8125/com.water.view.demo D/EventTag: childView_onTouchEvent:ACTION_UP

3,测试三:onInterceptTouchEvent中ACTION_MOVE返回true,其余返回false

8758-8758/com.water.view.demo D/EventTag: viewGroup_onInterceptTouchEvent:ACTION_DOWN
8758-8758/com.water.view.demo D/EventTag: childView_onTouchEvent:ACTION_DOWN
8758-8758/com.water.view.demo D/EventTag: viewGroup_onInterceptTouchEvent:ACTION_MOVE
8758-8758/com.water.view.demo D/EventTag: viewGroup_onTouchEvent:ACTION_MOVE
8758-8758/com.water.view.demo D/EventTag: viewGroup_onTouchEvent:ACTION_MOVE
8758-8758/com.water.view.demo D/EventTag: viewGroup_onTouchEvent:ACTION_UP

从上面的日志中,我们看出chilView中除了能接收到ACTION_DOWN,其余事件接受不到,都由父View进行处理。

最后

ViewGrop的事件分发原理相对View的分发原理多了一层拦截(onInterceptTouchEvent()),如果当前ViewGroup拦截后,相关的事件不会往下分发,会在当前ViewGrop中处理。其处理逻辑和View一致,ViewGroup本身继承View,拦截后调用的是super.dispatchTouchEvent。

事件分发的处理麻烦在于嵌套滑动,传统的处理是在子View中消费事件,同时根据功能控制相应的父View。这种写法通用性不强,官方出一套统一的标准,具体由NestedScrollingChild,NestedScrollingChildHelper,NestedScrollingParent,NestedScrollingParentHelper这几个类协同完成。具体的使用将在后续进一步说明。

事件分发的相关文章可参考:

Android-View事件分发机制

Android-事件分发-嵌套滑动

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值