美文网首页
事件传递

事件传递

作者: 霍霍9527 | 来源:发表于2019-11-25 12:38 被阅读0次

事件分发操作改变事件状态的主要是在ViewGroup
dispatchTouchEvent
onInterceptTouchEvent
View主要是负责事件的消费
dispatchTouchEvent
onTouchEvent

  //ViewGroup dispatchTouchEvent 派发事件方法分析
  @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

        boolean handled = false;
        //验证事件是否是安全事件
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            //点击事件开始,清除target、touchState等的状态
            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;
            //条件解读:1点击事件执行,
            //2.获取到的事件view的mFirstTouchTarget=null,会执行else语句-->intercepted = true;
            //而没有获取到事件的上级View会存储mFirstTouchTarget,会执行if语句
            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;
            //获取到事件的view,move事件一定不会执行
            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;
                //down事件执行下面的代码,move事件跳过下面的代码
                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);
                            //将事件派发给子View,递归执行dispatchTouchEvent方法
                            //子view消费了事件执行下面代码,并初始化mFirstTouchTarget 、newTouchTarget、alreadyDispatchedToNewTouchTarget = true
                            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.
            //down事件:自己再次验证自己是否要处理事件,执行View.dispatchTouchEvent -> onTouchEvent
           //move事件:自己消费自己事件
            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;
                    //子view消费了事件,并且是down事件执行
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        //判断是否取消事件传递给子view
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //派发儿子的move事件,move事件执行
                        //派发儿子的cancel事件,当上层View拦截了事件:intercepted = true ==> cancelChild = true 执行下面的方法就是执行Child的cancel事件。
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        //当前上层ViewGroup拦截,cancel子View的move事件
                        //mFirstTouchTarget清空,下次的move事件自己处理。
                        if (cancelChild) {
                            if (predecessor == null) {
                                //中断子View事件传递,将mFirstTouchTarget设为null,下次move事件就给自己派发事件,
                                //上面的代码if (mFirstTouchTarget == 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;
    }

      //可见,down事件层层派发并验证,直到有view消费事件
      //     move事件层层派发不验证,直接派发到消费事件的view

事件派发:ViewGroup 的 dispatchTouchEvent
down move up cancel
1,onFilterTouchEventForSecurity 验证事件的安全性
2,down事件清除之前缓存的时间状态,重置触摸状态
3,判断onInterceptTouchEvent
4,遍历该GroupView的子View,验证接收事件、判断触摸点是否在View内
5,拿到符合的child后执行dispatchTransformedTouchEvent(执行递归child.dispatchTouchEvent)
6,没有符合的child后执行dispatchTransformedTouchEvent参数传递自己执行 View.dispatchTouchEvent(event) 处理事件
7,5有消费的child后递归将child的所有层级的child赋值给其mFirstTouchTarget记录有事件消费了
8,move事件从跟View通过mFirstTouchTarget递归传递到消费Child的父view在传递给消费Child
9, 消费Child的父View获取move事件,消费Child控制getParent().requestDisallowInterceptTouchEvent(false);使得父view可以intercept, 具体操作就是intercept = true,父View将mFirstTouchTarget设置为null,执行自己的派发move事件

整理:down一定要传递到子View,要不子是不可能获取到其事件的,即父View 的 down时间onInterceptTouchEvent不能返回true

/**
 * 2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewGroup   stackTrace  dispatchTransformedTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewGroup   stackTrace  dispatchTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewGroup   stackTrace  dispatchTransformedTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewGroup   stackTrace  dispatchTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: com.android.internal.policy.DecorView   stackTrace  superDispatchTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: com.android.internal.policy.PhoneWindow   stackTrace  superDispatchTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.app.Activity   stackTrace  dispatchTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: androidx.appcompat.view.WindowCallbackWrapper   stackTrace  dispatchTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: com.android.internal.policy.DecorView   stackTrace  dispatchTouchEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.View   stackTrace  dispatchPointerEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$ViewPostImeInputStage   stackTrace  processPointerEvent
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$ViewPostImeInputStage   stackTrace  onProcess
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  deliver
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  onDeliverToNext
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  forward
2020-08-06 11:17:56.598 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$AsyncInputStage   stackTrace  forward
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  apply
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$AsyncInputStage   stackTrace  apply
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  deliver
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  onDeliverToNext
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  forward
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  apply
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$InputStage   stackTrace  deliver
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl   stackTrace  deliverInputEvent
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl   stackTrace  doProcessInputEvents
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl   stackTrace  enqueueInputEvent
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.ViewRootImpl$WindowInputEventReceiver   stackTrace  onInputEvent
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.view.InputEventReceiver   stackTrace  dispatchInputEvent
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.os.MessageQueue   stackTrace  nativePollOnce
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.os.MessageQueue   stackTrace  next
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.os.Looper   stackTrace  loop
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: android.app.ActivityThread   stackTrace  main
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: java.lang.reflect.Method   stackTrace  invoke
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: com.android.internal.os.Zygote$MethodAndArgsCaller   stackTrace  run
2020-08-06 11:17:56.599 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: com.android.internal.os.ZygoteInit   stackTrace  main
2020-08-06 11:17:56.600 25184-25184/com.huo.androidbasicstudy V/eventDispatchTest: DispatchTrueEventViewGroup   dispatchTouchEvent  dispatchTouchEvent

事件传递调用顺序
ViewRootImpl::processPointerEvent 
View::dispatchPointerEvent
DecorView::dispatchTouchEvent
WindowCallbackWrapper::dispatchTouchEvent
Activity::dispatchTouchEvent
PhoneWindow::superDispatchTouchEvent
DecorView::superDispatchTouchEvent
ViewGroup::dispatchTouchEvent
ViewGroup::dispatchTransformedTouchEvent
...等等

*/

伴随一次手势,事件分发主要有三种类型的事件,down move up 事件
时间的调用顺序如上面展示的样子。
down事件尽可能的向子view分发,除非有事件拦截onInterceptTouchEvent 返回true,或者dispatchTouchEvent返回true或者false,

  • dispatchTouchEvent返回true:由于没有执行父View的dispatchTouchEvent并且自己也没有出里onTouch事件的话,事件会一直传递到该View,并且没有onInterceptTouchEvent和onTouch的事件执行包裹activity的,
  • dispatchTouchEvent返回super,交给ViewGroup处理,看onTouch()是否消费事件,没有的话最终由activity消费掉事件。
  • dispatchTouchEvent返回false:代表不处理事件,最终事件由activity消费掉。
    activity消费掉事件的原理 : 所有的View或者ViewGroup都没有处理down事件在onTouch()中,或者说onTouch()返回false。在分发move或者up事件的时候,在事件分发到DecorView,调用superDispatchTouchEvent()执行ViewGroup的dispatchTouchEvent()就返回了false(mFirstTouchTarget == null),在DecorView就结束了事件传递,并由activity来消费事件,这也是在没有处理down事件的时候也接收不到move和up事件的原因。
  • onInterceptTouchEvent 返回true,dispatchTouchEvent中拦截事件,交给自己的onTouch()处理
  • onInterceptTouchEvent 返回false, 不拦截事件,事件继续派发dispatchTouchEvent()。
  • onInterceptTouchEvent 返回super,交给父类处理拦截事件。
  • onInterceptTouchEvent 方法执行条件,(down事件 or mFirstTouchTarget != null ) & !disallowIntercept
  • onTouch() 返回true,消费事件,后续事件都传递到这里。
  • onTouch() 返回false,不消费事件,事件向外层View传递。
  • onTouch() 返回super,交给父类判断是否要消费。

down事件设置mFirstTouchTarget

相关文章

网友评论

      本文标题:事件传递

      本文链接:https://www.haomeiwen.com/subject/lbzlwctx.html