android SDK-25事件分发机制–源码正确解析

Android 事件分发分为View和ViewGroup的事件分发,ViewGroup比View过一个拦截判断,viewgroup可以拦截事件,从而决定要不要把事件传递给子view,因为view没有子view所以不存在拦截事件的情况。

事件分发主要从事件的分发,拦截,和处理三个函数的调用逻辑关系来分析。

public boolean dispatchTouchEvent(MotionEvent event) {}public boolean onInterceptTouchEvent(MotionEvent ev) {}public boolean onTouchEvent(MotionEvent event) {}

首先,屏幕上面一个点击事件,通过传感器捕获到点击,然后知道把点击事件传递到activity 到PhoneWindow,再到,DecorView 最后就到我们自己在布局文件中的view或者viewgroup。

下面分析dispatchTouchEvent源码 :(sdk-25)(==>这个标记为重点,不用全懂,只要把==>这个标记处的逻辑理清楚就行)

 @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);}//辅助功能点击事件的判断和处理根本不用管,直接不要管,跳转到下一个重点// ==> 一个标志,初始值为不处理,意识就是不处理MotionEventboolean handled = false;if (onFilterTouchEventForSecurity(ev)) {final int action = ev.getAction();final int actionMasked = action & MotionEvent.ACTION_MASK;// Handle an initial down.// ==> 处理第一个点击事件(事件分为,点击事件,move事件,up事件,所以点击事件是第一个事件)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;// ==> 判断要不要打断,如果不是点击事件,并且mFirstTouchTarget为null,则该viewgroup则打断拦截事件。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;// ==>如果是down事件,进行遍历子view,并且把事件分发给子view,前提是down事件的坐标必须在子view中等等条件==>这句话,请把下面的源码分析完再一定回来看一看,你要思考一下,这里如果是down事件才会进去,如果是move事件那么不会进去分发了,其实往后看源码会发现,在down事件分发给一个child,如果这个child消费了这个down事件,那么这个child就会被保存起来,以后的move(可能0到多次move),up都会直接分发给这个child,就不用每次再去遍历所有的Child这些效率就提高和很多,但是你也会想到,如果一个down事件被某个child消费只有,其它child就无法被分发事件了,除非我们手动调用child的分发方法,或者打断事件序列,从发分发一个down事件,这段话请看完后面的源码再来推敲一下,就完全理解事件分发机制了。if (actionMasked == MotionEvent.ACTION_DOWN|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {final int actionIndex = ev.getActionIndex(); // always 0 for downfinal 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;}// ==>判断这个子view能否接受点击事件和子view是否包含这个点击的坐标,具体的判断点击这两个方法进去看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);// ==>  关键之处,这里将事件传递给child进行处理了,马上进入这个方法看看吧if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))

// ==>dispatchTransformedTouchEvent方法

 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) {// ==>如果child为空,直接调用该viewgroup自己父类的dispatchTouchEvent,也就是viewdispatchTouchEvent方法,点击进去会发现它会调用onTouchEvent,也就是说如果viewGroup如果没有child那么他就会调用自己的onTouchEvent方法来消费这个事件,这个handle就表明了这个事件viewgroup自己是否消费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());}// ==>我们的child不为空的时候,就调用child事件分发方法,于是到这里可以看到事件的传递了,先来分析简单的情况,如果child是view不是viewgroup,那么dispatchTouchEvent流程就简单了,会调用onTouchEvent来告诉父view,child它是否消费父亲分发给他的事件,这个handle就表明了这个事件clild是否消费handled = child.dispatchTouchEvent(transformedEvent);}// Done.transformedEvent.recycle();return handled;
}

//这个重要的方法分析完之后,马上返回刚才源码的地方,继续。。。

//如果刚才,我们的child不为空并且child消费down事件,那么就很棒了,说明有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 indexfor (int j = 0; j < childrenCount; j++) {if (children[childIndex] == mChildren[j]) {mLastTouchDownIndex = j;break;}}} else {mLastTouchDownIndex = childIndex;}mLastTouchDownX = ev.getX();mLastTouchDownY = ev.getY();// ==>重点,从上面的if条件可以看出,有child消费down事件才会执行到这里,这个方法点进去发现mFirstTouchTarget = target;     这句代码,很重要哦。很明显就是把消费down事件的child赋值给mFirstTouchTarget,从而保存起来newTouchTarget = addTouchTarget(child, idBitsToAssign);// ==> alreadyDispatchedToNewTouchTarget = true; 已经把事件分发给新的触摸目标下面在分发的时候会用到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();}//这里,如果是down事件,并且mFirstTouchTarget != null则加入链表newTouchTarget,这里不要管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;}}}// ==> 由于刚才mFirstTouchTarget被赋值为消息了down事件的child,所以不为空了// Dispatch to touch targets.if (mFirstTouchTarget == null) {// 这里非常重要,如果child为空,表明viewgroup在分发事件给child的dispatchTouchEvent被返回了false,说明子view都不消费down事件,那么这里会调用dispatchTransformedTouchEvent这个重要的方法,点进去就会发现,当child为null的时候,会调用viewgroup自己的父类View的dispatchTouchEvent,从而调用onTouchEvent,就是说儿子不消费,给老子再看看要不要消费。// 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;// ==>看到这里,你是不是发现怎么又调用了这个重要的,吧事件分发给child的方法,刚才不是已经分发了,这不是第二次又来分发吗?,当然不会,你看前面的,第一次分发事件的时候已经讲alreadyDispatchedToNewTouchTarget=true;了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自己先判断要不要拦截事件,和有没有调用过requestDisallowInterceptTouchEvent方法来不拦截事件,如果不拦截,当down事件的时候,遍历child,看child是否消费,child如果消息,则被保存下来,后面的事件就不遍历直接分发给他,如果child不消费,那么viewgruop继续执行,调用自己onTouchEvent方法来判断自己是不是要消费事件。

android SDK-25事件分发机制--源码正确解析相关推荐

  1. Android View系列(二):事件分发机制源码解析

    概述 在介绍点击事件规则之前,我们需要知道我们分析的是MotionEvent,即点击事件,所谓的事件分发就是对MotionEvent事件的分发过程,即当一个MotionEvent生成以后,系统需要把这 ...

  2. 深入解析Android事件分发机制源码(1)

    有关事件分发的文章,网上已经有了太多太多,但是看了很多,大部分都只是讲解了最外层表现给开发者看的结果,并没有深入讲解,为何会得到这个现象.基于透过现象看本质的思想,趁着手头没有太多活,写下这篇博客,一 ...

  3. android 事件分发 代码解析,Android事件分发之源码分析

    原文首发于微信公众号:躬行之,欢迎关注交流! 上篇文章中叙述了 Android 事件分发的大致流程,下面从 Activity.ViewGroup.View 三个方面介绍事件的相关方法,小节如下: Ac ...

  4. Android View的事件分发机制解析

    作者:网易·周龙 最近刚看完android-Ultra-Pull-To-Refresh下拉刷新的源码,发现在写自定义控件时,对于View的事件的传递总是搞不太清楚,而View事件的分发机制,又是解决可 ...

  5. Android View的事件分发机制和滑动冲突解决方案

    这篇文章会先讲Android中View的事件分发机制,然后再介绍Android滑动冲突的形成原因并给出解决方案.因水平有限,讲的不会太过深入,只希望各位看了之后对事件分发机制的流程有个大概的概念,并且 ...

  6. Android事件分发之源码分析,kotlin库

    //这里又调用了FrameLayout中的dispatchTouchEvent方法 return super.dispatchTouchEvent(event); } - } 由于在 FrameLay ...

  7. View的Touch事件分发(二.源码分析)

    Android中Touch事件的分发又分为View和ViewGroup的事件分发,先来看简单的View的touch事件分发. 主要分析View的dispatchTouchEvent()方法和onTou ...

  8. Android多线程:深入分析 Handler机制源码(二)

    前言 在Android开发的多线程应用场景中,Handler机制十分常用 接下来,深入分析 Handler机制的源码,希望加深理解 目录 1. Handler 机制简介 定义 一套 Android 消 ...

  9. Android-事件分发机制(源码层面)

    事件分发的流程: Activity->window->view 例1:当我们对控件的onClick和onTouch事件进行注册时,点击控件两个方法都执行,且onTouch优先于onClic ...

最新文章

  1. nagios mysql php_nagios监控mysql
  2. 使用git管理源码之文件状态和工作区理解
  3. Atitit sql计划任务与查询优化器--统计信息模块
  4. Swift 3.1新改动
  5. python dlib学习(十一):眨眼检测
  6. SQL数据库权限回收revoke
  7. 【技术种草】介绍一款开源电商网站的购物车添加功能的实现
  8. PAT乙类1008之数组元素循环右移问题
  9. Android异常总结---1.异常原因: java.lang.IllegalArgumentException: URI: content://com.android.contacts/con
  10. ecshop 支持 php,ecshop支持PHP7的修改方法
  11. 【深度优先搜索】计蒜客:王子救公主
  12. hdu 1078 FatMouse and Cheese(记忆化搜索)
  13. 树莓派无法打开摄像头模块,无法识别摄像头
  14. STK之Commu模块之仿真同步卫星与地面站通信
  15. CAN总线学习总结2——CAN错误及CAN busoff处理机制
  16. 计算机成绩统计优秀率,高校学生考试成绩的数据分析模式与可视化研究
  17. SwiftUI SF Symbols 好处及其使用指南
  18. oracle转换成字符型,Oracle中将Clob字段转换成字符串
  19. C# Action 使用
  20. CPU占用率过高的原因和后果

热门文章

  1. 网络基础——综合布线
  2. C语言捉弄人的程序,愚人节怎么捉弄人?愚人节微信红包整人方法大全
  3. Spanky - beloved ~桜の彼方へ~ -full ver
  4. おひきは本当にいじめ彼女と呼ばれる
  5. 福州大学计算机考研调剂,2014福州大学计算机考研调剂复试纪实
  6. nokia6android9,诺基亚6.1推送Android 9.0:Nokia 7.1 Plus更新马上就来
  7. 日常训练 20170708 贝加尔湖畔baikal
  8. css和html是什么关系,css是什么,CSS和HTML有什么关系
  9. 为什么很多动物不用学就会游泳?比如猪?人却不行?
  10. 【科技与狠货】云盘变硬盘