2019独角兽企业重金招聘Python工程师标准>>>

ViewRoot里面有一个InputHandler,它开启一个线程来接受native曾发送过来的消息,然后调用handlePoniter类似名字的方法,这个方法也会发一个异步消息DISPACTH_POINT,然后调用viewroot的deliverPointerEvent(),然后调用DecorView对象mView的dispacthTouchEvent(),不同的是,它没有在这之前拦截消息给输入法窗口。DecorView的dispacthTouchEvent如下:

@Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            final Callback cb = getCallback();
            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
                    : super.dispatchTouchEvent(ev);
        }

这里看看有没有实现Window.CallBack接口,如果没有则调用   public boolean superDispatchTouchEvent(MotionEvent event) {
            return super.dispatchTouchEvent(event);
        }

也就是去ViewGroup中去遍历了

2.又是Window.callBack对象的dispacthTouchEvent(),是不是很眼熟,这个跟keyEvent里面的一样,这个CallBack接口,Activity实现了这个接口,程序流走到Actiivyt里面的dispactchTochEvent中:

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

这里还是调用PhoneWindow对象也就是Actiivty的Window对象的superDispatchTouchEvent:

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

其实还是DecorView的mDecor.superDispatchTouchEvent(event);,这个方法又回到了第一步走最后那段源码中,也就是遍历ViewTree去寻找消费这个touEvent的targetView
当然,如果没有找到,那么调用Activity里面的 onTouchEvent(ev);

public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

return false;
    }

3.以上是总的流程,至于ViewGroup里面的dispacthTouchEvent(),源码如下,请看里面的注释:
        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.
            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) {

//如果你的ViewGroup中有设置onInterceptTouchEvent这个方法的ActionDown时间并返回true,则此处不再下发,而是ViewGroup自身消费掉
               1.     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 = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();

final View[] children = mChildren;

2.如果没有拦截,则走遍历递归子View
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder
                                    ? getChildDrawingOrder(childrenCount, i) : i;
                            final View child = (preorderedList == null)
                                    ? children[childIndex] : preorderedList.get(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);

//for循环里面对childview检查是否消费触摸事件,如果为true则break跳出循环,这之前要把找到的touch保存到一个touchTarget对象中
                            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;
                    }
                }
            }

3.上面遍历找到的targetview会存放到newTouchTarget中,如果没找到则会把firstTouchTarget给它,firstTouchTarget是least recently added target,如果mFirstTouchTarget 也为空,那么就把viewgroup自己当成一个普通的view来调用,也就是调用View.dispatchTouchEvent方法,如果不然,则对touchTarget的链表中的next就行循环找到targetView,并且调用这个dispatchTransformedTouchEvent来遍历递归是否消费本次事件,如果消费则handle=ture.如果最终没消费,则调用onUnhandedEvent方法,而firstTouchTarget是在for循环中给newTochTarget赋值的时候通过    private TouchTarget addTouchTarget(View child, int pointerIdBits) {
        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

所以正常情况下firstTouchTarget不会为空,如果为空说明下面没有找到,那么只能自己消费掉

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

}

综上所述,dispatchKeyEvent与dispatchTouchEvent在ViewTree中找targetView是不同的,dispacthKey在从上往下,上层的viewgroup有focus则自己消费掉,而dispatchTouchEvent则是先在child里面找,如果child没有消费,这个时候它才会给自己。

转载于:https://my.oschina.net/u/2971691/blog/886305

Android分发事件相关推荐

  1. android 点击事件消费,Android View事件分发和消费源码简单理解

    Android View事件分发和消费源码简单理解 前言: 开发过程中觉得View事件这块是特别烧脑的,看了好久,才自认为看明白.中间上网查了下singwhatiwanna粉丝的读书笔记,有种茅塞顿开 ...

  2. android触摸事件分发,Android 事件分发机制

    Android 事件分发机制一直让人头痛,之前也是面向 GitHub 编程得过且过.今天下定决心了解一下,以便后面自己定制 View 效果.Android 触摸事件有三个基本类型:ACTION_DOW ...

  3. 浅谈android的事件分发机制

    一.点击事件介绍 在Android 的点击事件中我们涉及到ViewGroup类的三个方法: @Overridepublic boolean dispatchTouchEvent(MotionEvent ...

  4. Android的事件分发

    1. Touch事件和绘制事件的异同之处 Touch事件和绘制事件很类似,都是由ViewRoot派发下来的,但是不同之处在绘制事件是由应用中的某个View发起请求,一层一层上传到ViewRoot,再有 ...

  5. Android的事件分发实例分析

    如果对Android的事件分发不熟悉,可以看Android的事件分发 瀑布流 实现的功能:滑动左边的RecyclerView区域,左边的RecyclerView滚动:滑动中间的RecyclerView ...

  6. Android之事件分发机制

    本文主要包括以下内容 view的事件分发 viewGroup的事件分发 首先来看两张图 在执行touch事件时 首先执行dispatchTouchEvent方法,执行事件分发. 再执行onInterc ...

  7. Android 系统(218)---Android的事件分发机制以及滑动冲突的解决

    Android的事件分发机制以及滑动冲突的解决 声明:  本文主要涉及VIew的事件分发与滑动冲突的解决,关于View的事件分发流程的部分内容参考自:  Android事件分发机制详解:史上最全面.最 ...

  8. Android系统(120)-android的事件分发机制

    android的事件分发机制 android的事件分发机制 比如说,现在你所在的公司中有一项任务被派发下来了,项目经理把项目交给你的老大,你的老大老大手下有很多人,看了看觉得你做很合适,把这个任务交给 ...

  9. Android的事件分发机制

    前言 Android事件分发机制是Android开发者必须了解的基础 网上有大量关于Android事件分发机制的文章,但存在一些问题:内容不全.思路不清晰.无源码分析.简单问题复杂化等等 今天,我将把 ...

最新文章

  1. nvGRAPH原理概述
  2. 表格中td限宽溢出以省略号代替
  3. R语言ggplot2可视化:可视化离散(分类)变量的堆叠的柱状图、横轴是离散变量、柱状图是多个分组的计数和叠加
  4. WCF进阶:为每个操作附加身份信息
  5. diou ciou torch
  6. 1号店交易系统架构如何向「高并发高可用」演进
  7. windows10 下 用图片手把手教你 卸载 cygwin
  8. html div画三角,css画三角形
  9. 计算机网络讨论4,计算机网络实验四
  10. python-函数的局部变量
  11. [ActionScript 3.0] AS3.0 对象在一定范围随机显示不重叠
  12. 51单片机学习笔记0 -- 仿真软件安装(Protues8.0)
  13. ardupilot固件二次开发_【国外开源】无人机 ArduPilot Mega 控制板原理图/PCB/固件源码...
  14. 数字键盘(触屏键盘)
  15. 来来来,一起去看临泉王冲林岗的红枫叶
  16. 三星S6D1121主控彩屏(240*320*18bit,262K)驱动程序
  17. Java实现字典树 Trie
  18. 用C++实现魔方并输出步骤
  19. HTML5字体设置重影,Word怎么设置字体重影
  20. 高德地图和百度地图生成网址

热门文章

  1. robotac属于a类还是b类_所得税A类和B类的区别,什么样的属于B类??
  2. Layui form 表单验证 基本属性
  3. java中table属性_div实现table功能
  4. 手机信令数据怎么获得_手机信令数据辅助下的张江科学城职住分析及对策 | 上海城市规划...
  5. python中flush什么意思,Python的file.flush()到底在做什么?
  6. python3web库_基于 Python3 写的极简版 webserver
  7. 对讲机怎么用_对讲机防水透气解决方案是怎么做的?
  8. python调用so库输出传入指针_python中使用ctypes调用so传参设置遇到的问题及解决方法...
  9. tld自定义标签之基础入门篇
  10. 风变Python 之旅5----for...in 以及while的循环学习