Android View的事件分流源码

提纲

  • 事件分发的事件有哪些,涉及到哪些方法
  • 事件分发怎么从Activity传入到View
  • View的事件分发
  • ViewGroup的事件分发

1. 事件分发的事件有哪些,涉及到哪些方法

  • 当用户触摸点击屏幕时,将会产生事件,在android中为MotionEvent在这个类中有很多静态常量:

名称值含义ACTION_DOWN0按下的手势已开始,动作包含初始开始位置。ACTION_UP1按下手势完成后,运动包含最终的释放位置以及自上一次下移或移动事件以来的所有中间点ACTION_MOVE2A change has happened during a press gesture (between {@link #ACTION_DOWN} and {@link #ACTION_UP})ACTION_CANCEL3当前手势已中止。…

  • 默认情况下事件分发会按照由Activity到ViewGroup再到View的顺序进行分发
  • 事件的传递流程是从PhoneWindow->DecorView(mDecor是getWindow().getDecorView()返回的View,通过setContentView设置的View是该View的子View),再传递到Activity的View树。

1.View的事件分发的重要的方法:diapatchTouchEvent和touchEvent,onClick

|---View
|   |---boolean dispatchTouchEvent(MotionEvent event)
|   |--- boolean onTouchEvent(MotionEvent event)

1.1 dispatchTouchEvent: 如果事件由视图处理,则为true,否则为false。

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;
            }
            // 重点 判断listenerInfo 中是否有事件listenter 并且mOnTouchListener.onTouc 返回true 
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
						// 第二个重点,如果上述判断为false,并且 onTouchEventr返回为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;
    }

  1. dispatchTouchEvent中final int actionMasked = event.getActionMasked();
  2. ListenerInfo :将view所有的listener信息封装到一个对象中。
  3. 在该方法中有两个判断:
 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;
            }
复制代码

如果onTouchEvent或者是onTouchListenner是true的话,会消费此事件,同时,在这里也走了onTouchEvent

  • boolean onTouchEvent
  • MotionEvent.ACTION_UP:调用了PerformClick()

三个问题:

1. 在activity中调用了

 mTouchView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.e("TAG", "onTouch: " + event.getAction());
                return false;
            }
        });
        mTouchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("TAG", "onClick: " );
            }
        });

     /***********TabLayout************/   
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.e("TAG", "onTouchEvent: "+event.getAction());
        return super.onTouchEvent(event);
    }
复制代码

执行顺序:

2. 如果是Tablyout中直接return ture呢?

不执行onClick,因为onClick在View.OntouchEvent中的ACTION_UP中,若直接return true 就不会走super中的方法。

3. 如果是dispatchEvent return true呢?

什么都不执行

分发流程

super.dispatchEvent->ListenerInfo->super.onTouchEvent(event)->ACTION_UP->performListener().
复制代码

2. ViewGroup的事件分发:

首先是actionDown:

 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;
                }
            }
复制代码
  • mFirstTouchTarget: 这个很重要,只有在第一次按下的时候才会调用disallowIntercept,如果之后想要改变效果的时候,这是一个坑。
|---ViewGroup
|   |---dispatchTouchEvent
|   |   |---onInterceptTouchEvent(ev)

有View会消耗时间的情况(比如点击,onTouchListener)

  • 第一次按下进来(down)—>ViewGroup.dispatchTouchEvent—>ViewGroup.onInterceptTouchEvent(ev)–>view.dispatchEvent—(view的那一套)

  • 第二次进来(move)ViewGroup.dispatchTouchEvent—>ViewGroup.onInterceptTouchEvent(ev)–>view.dispatchEvent—(view的那一套)

  • 第三次(up)ViewGroup.dispatchTouchEvent—>ViewGroup.onInterceptTouchEvent(ev)–>view.dispatchEvent—(view的那一套)–>view.onClick


View中没有消费事件的情况。只走一遍

  • 第一次进来(down)ViewGroup.dispatchTouchEvent—>ViewGroup.onInterceptTouchEvent(ev)–>view.dispatchEvent—view.onTouch–>onTouch Event

viewGroup的源码分析

actionDown

 /**
     * Clears all touch targets.
     */
    private void clearTouchTargets() {
        TouchTarget target = mFirstTouchTarget;
        if (target != null) {
            do {
                TouchTarget next = target.next;
                target.recycle();
                target = next;
            } while (target != null);
            mFirstTouchTarget = null; //清除target
        }
    }

      if (!canceled && !intercepted) // intercepted 默认是没有拦截
      {
         if (newTouchTarget == null && childrenCount != 0) {
              for (int i = childrenCount - 1; i >= 0; i--) {//反序列的for循环 先拿最上面的layout
                if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                }
              }
         }
      }


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

最后在这里为了帮助大家深刻理解Android相关知识点的原理以及面试相关知识,这里放上相关的我搜集整理的腾讯、字节跳动、阿里、百度2019-2020面试真题解析,我把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节

Android View的事件分流源码_第1张图片

详细整理在GitHub可见;

Android架构视频+BAT面试专题PDF+Kotlin入门到精通、Flutter入门到实战学习笔记

Android View的事件分流源码_第2张图片

你可能感兴趣的:(程序员,android,移动开发)