viewgroup的touch事件处理机制

Android事件分发详解(三)——ViewGroup的dispatchTouchEvent()源码学习

分类: Android Android进阶学习 311人阅读 评论(1) 收藏 举报
  1. package cc.aa;  
  2.   
  3. import android.os.Environment;  
  4. import android.view.MotionEvent;  
  5. import android.view.View;  
  6.   
  7. public class UnderstandDispatchTouchEvent {  
  8.     /** 
  9.      * dispatchTouchEvent()源码学习及其注释 
  10.      * 常说事件传递中的流程是:dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent 
  11.      * 在这个链条中dispatchTouchEvent()是处在链首的位置当然也是最重要的. 
  12.      * 在dispatchTouchEvent()决定了Touch事件是由自己的onTouchEvent()处理 
  13.      * 还是分发给子View处理让子View调用其自身的dispatchTouchEvent()处理. 
  14.      *  
  15.      *  
  16.      * 其实dispatchTouchEvent()和onInterceptTouchEvent()以及onTouchEvent()的关系 
  17.      * 在dispatchTouchEvent()方法的源码中体现得很明显. 
  18.      * 比如dispatchTouchEvent()会调用onInterceptTouchEvent()来判断是否要拦截. 
  19.      * 比如dispatchTouchEvent()会调用dispatchTransformedTouchEvent()方法且在该方法中递归调用 
  20.      * dispatchTouchEvent();从而会在dispatchTouchEvent()里最终调用到onTouchEvent() 
  21.      *  
  22.      *  
  23.      *  
  24.      * 重点关注: 
  25.      * 1 子View对于ACTION_DOWN的处理十分重要!!!!! 
  26.      *   ACTION_DOWN是一系列Touch事件的开端,如果子View对于该ACTION_DOWN事件在onTouchEvent()中返回了false即未消费. 
  27.      *   那么ViewGroup就不会把后续的ACTION_MOVE和ACTION_UP派发给该子View.在这种情况下ViewGroup就和普通的View一样了, 
  28.      *   调用该ViewGroup自己的dispatchTouchEvent()从而调用自己的onTouchEvent();即不会将事件分发给子View. 
  29.      *   详细代码请参见如下代码分析. 
  30.      *    
  31.      * 2 为什么子view对于Touch事件处理返回true那么其上层的ViewGroup就无法处理Touch事件了????? 
  32.      *   这个想必大家都知道了,因为该Touch事件被子View消费了其上层的ViewGroup就无法处理该Touch事件了. 
  33.      *   那么在源码中的依据是什么呢??请看下面的源码分析 
  34.      *    
  35.      * 参考资料: 
  36.      * 0 http://blog.csdn.net/sahadev_/article/details/23839039 
  37.      * 1 http://www.cnblogs.com/xiaoweiz/p/3838682.html 
  38.      * 2 http://hukai.me/android-deeper-touch-event-dispatch-process/ 
  39.      * 3 http://blog.csdn.net/hdxiaoyu2/article/details/25563453 
  40.      * 4 http://www.eoeandroid.com/thread-542296-1-1.html 
  41.      * 5 http://www.eoeandroid.com/forum.php?mod=viewthread&tid=319301 
  42.      * 6 http://stackvoid.com/details-dispatch-onTouch-Event-in-Android/ 
  43.      *   Thank you very much 
  44.      */  
  45.       
  46.     @Override  
  47.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  48.         if (mInputEventConsistencyVerifier != null) {  
  49.             mInputEventConsistencyVerifier.onTouchEvent(ev, 1);  
  50.         }  
  51.   
  52.         boolean handled = false;  
  53.         if (onFilterTouchEventForSecurity(ev)) {  
  54.             final int action = ev.getAction();  
  55.             final int actionMasked = action & MotionEvent.ACTION_MASK;  
  56.   
  57.             /** 
  58.              * 第一步:对于ACTION_DOWN进行处理(Handle an initial down) 
  59.              * 因为ACTION_DOWN是一系列事件的开端,当是ACTION_DOWN时进行一些初始化操作. 
  60.              * 从源码的注释也可以看出来:清除以往的Touch状态(state)开始新的手势(gesture) 
  61.              * cancelAndClearTouchTargets(ev)中有一个非常重要的操作: 
  62.              * 将mFirstTouchTarget设置为null!!!! 
  63.              * 随后在resetTouchState()中重置Touch状态标识 
  64.              */  
  65.             if (actionMasked == MotionEvent.ACTION_DOWN) {  
  66.                 // Throw away all previous state when starting a new touch gesture.  
  67.                 // The framework may have dropped the up or cancel event for the previous gesture  
  68.                 // due to an app switch, ANR, or some other state change.  
  69.                 cancelAndClearTouchTargets(ev);  
  70.                 resetTouchState();  
  71.             }  
  72.   
  73.               
  74.             /** 
  75.              * 第二步:检查是否要拦截(Check for interception) 
  76.              * 在dispatchTouchEvent(MotionEventev)这段代码中 
  77.              * 使用变量intercepted来标记ViewGroup是否拦截Touch事件的传递. 
  78.              * 该变量在后续代码中起着很重要的作用. 
  79.              */  
  80.             final boolean intercepted;  
  81.             // 事件为ACTION_DOWN或者mFirstTouchTarget不为null(即已经找到能够接收touch事件的目标组件)时if成立  
  82.             if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {  
  83.                 //判断disallowIntercept(禁止拦截)标志位  
  84.                 //因为在其他地方可能调用了requestDisallowInterceptTouchEvent(boolean disallowIntercept)  
  85.                 //从而禁止执行是否需要拦截的判断(有点拗口~其实看requestDisallowInterceptTouchEvent()方法名就可明白)  
  86.                 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
  87.                 //当没有禁止拦截判断时(即disallowIntercept为false)调用onInterceptTouchEvent(ev)方法  
  88.                 if (!disallowIntercept) {  
  89.                     //既然disallowIntercept为false那么就调用onInterceptTouchEvent()方法将结果赋值给intercepted  
  90.                     //常说事件传递中的流程是:dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent  
  91.                     //其实在这就是一个体现,在dispatchTouchEvent()中调用了onInterceptTouchEvent()  
  92.                     intercepted = onInterceptTouchEvent(ev);  
  93.                     ev.setAction(action); // restore action in case it was changed  
  94.                 } else {  
  95.                      //当禁止拦截判断时(即disallowIntercept为true)设置intercepted = false  
  96.                     intercepted = false;  
  97.                 }  
  98.             } else {  
  99.                 //当事件不是ACTION_DOWN并且mFirstTouchTarget为null(即没有Touch的目标组件)时  
  100.                 //设置 intercepted = true表示ViewGroup执行Touch事件拦截的操作。  
  101.                 //There are no touch targets and this action is not an initial down  
  102.                 //so this view group continues to intercept touches.  
  103.                 intercepted = true;  
  104.             }  
  105.   
  106.               
  107.             /** 
  108.              * 第三步:检查cancel(Check for cancelation) 
  109.              *  
  110.              */  
  111.             final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL;  
  112.   
  113.               
  114.             /** 
  115.              * 第四步:事件分发(Update list of touch targets for pointer down, if needed) 
  116.              */  
  117.             final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;  
  118.             TouchTarget newTouchTarget = null;  
  119.             boolean alreadyDispatchedToNewTouchTarget = false;  
  120.             //不是ACTION_CANCEL并且ViewGroup的拦截标志位intercepted为false(不拦截)  
  121.             if (!canceled && !intercepted) {  
  122.                 //处理ACTION_DOWN事件.这个环节比较繁琐.  
  123.                 if (actionMasked == MotionEvent.ACTION_DOWN  
  124.                     || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)  
  125.                     || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  126.                     final int actionIndex = ev.getActionIndex(); // always 0 for down  
  127.                     final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex):TouchTarget.ALL_POINTER_IDS;  
  128.   
  129.                     // Clean up earlier touch targets for this pointer id in case they  
  130.                     // have become out of sync.  
  131.                     removePointersFromTouchTargets(idBitsToAssign);  
  132.   
  133.                     final int childrenCount = mChildrenCount;  
  134.                     if (childrenCount != 0) {  
  135.                         // 依据Touch坐标寻找子View来接收Touch事件  
  136.                         // Find a child that can receive the event.  
  137.                         // Scan children from front to back.  
  138.                         final View[] children = mChildren;  
  139.                         final float x = ev.getX(actionIndex);  
  140.                         final float y = ev.getY(actionIndex);  
  141.   
  142.                         final boolean customOrder = isChildrenDrawingOrderEnabled();  
  143.                         // 遍历子View判断哪个子View接受Touch事件  
  144.                         for (int i = childrenCount - 1; i >= 0; i--) {  
  145.                             final int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;  
  146.                             final View child = children[childIndex];  
  147.                             if (!canViewReceivePointerEvents(child) || !isTransformedTouchPointInView(x, y, child, null)) {  
  148.                                 continue;  
  149.                             }  
  150.   
  151.                             newTouchTarget = getTouchTarget(child);  
  152.                             if (newTouchTarget != null) {  
  153.                                 // 找到接收Touch事件的子View!!!!!!!即为newTouchTarget.  
  154.                                 // 既然已经找到了,所以执行break跳出for循环  
  155.                                 // Child is already receiving touch within its bounds.  
  156.                                 // Give it the new pointer in addition to the ones it is handling.  
  157.                                 newTouchTarget.pointerIdBits |= idBitsToAssign;  
  158.                                 break;  
  159.                             }  
  160.   
  161.                             resetCancelNextUpFlag(child);  
  162.                             /** 
  163.                              * 如果上面的if不满足,当然也不会执行break语句. 
  164.                              * 于是代码会执行到这里来. 
  165.                              *  
  166.                              * 调用方法dispatchTransformedTouchEvent()将Touch事件传递给子View做 
  167.                              * 递归处理(也就是遍历该子View的View树) 
  168.                              * 该方法很重要,看一下源码中关于该方法的描述: 
  169.                              * Transforms a motion event into the coordinate space of a particular child view, 
  170.                              * filters out irrelevant pointer ids, and overrides its action if necessary. 
  171.                              * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 
  172.                              * 将Touch事件传递给特定的子View. 
  173.                              * 该方法十分重要!!!!在该方法中为一个递归调用,会递归调用dispatchTouchEvent()方法!!!!!!!!!!!!!! 
  174.                              * 在dispatchTouchEvent()中: 
  175.                              * 如果子View为ViewGroup并且Touch没有被拦截那么递归调用dispatchTouchEvent() 
  176.                              * 如果子View为View那么就会调用其onTouchEvent(),这个就不再赘述了. 
  177.                              *  
  178.                              *  
  179.                              * 该方法返回true则表示子View消费掉该事件,同时进入该if判断. 
  180.                              * 满足if语句后重要的操作有: 
  181.                              * 1 给newTouchTarget赋值 
  182.                              * 2 给alreadyDispatchedToNewTouchTarget赋值为true. 
  183.                              *   看这个比较长的英语名字也可知其含义:已经将Touch派发给新的TouchTarget 
  184.                              * 3 执行break. 
  185.                              *   因为该for循环遍历子View判断哪个子View接受Touch事件,既然已经找到了 
  186.                              *   那么就跳出该for循环. 
  187.                              * 4 注意: 
  188.                              *   如果dispatchTransformedTouchEvent()返回false即子View 
  189.                              *   的onTouchEvent返回false(即Touch事件未被消费)那么就不满足该if条件,也就无法执行addTouchTarget() 
  190.                              *   从而导致mFirstTouchTarget为null.那么该子View就无法继续处理ACTION_MOVE事件 
  191.                              *   和ACTION_UP事件!!!!!!!!!!!!!!!!!!!!!! 
  192.                              * 5 注意: 
  193.                              *   如果dispatchTransformedTouchEvent()返回true即子View 
  194.                              *   的onTouchEvent返回true(即Touch事件被消费)那么就满足该if条件. 
  195.                              *   从而mFirstTouchTarget不为null!!!!!!!!!!!!!!!!!!! 
  196.                              * 6 小结: 
  197.                              *   对于此处ACTION_DOWN的处理具体体现在dispatchTransformedTouchEvent() 
  198.                              *   该方法返回boolean,如下: 
  199.                              *   true---->事件被消费----->mFirstTouchTarget!=null 
  200.                              *   false--->事件未被消费---->mFirstTouchTarget==null 
  201.                              *   因为在dispatchTransformedTouchEvent()会调用递归调用dispatchTouchEvent()和onTouchEvent() 
  202.                              *   所以dispatchTransformedTouchEvent()的返回值实际上是由onTouchEvent()决定的. 
  203.                              *   简单地说onTouchEvent()是否消费了Touch事件(true or false)的返回值决定了dispatchTransformedTouchEvent() 
  204.                              *   的返回值!!!!!!!!!!!!!从而决定了mFirstTouchTarget是否为null!!!!!!!!!!!!!!!!从而进一步决定了ViewGroup是否 
  205.                              *   处理Touch事件.这一点在下面的代码中很有体现. 
  206.                              *    
  207.                              *  
  208.                              */  
  209.                             if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {  
  210.                                 // Child wants to receive touch within its bounds.  
  211.                                 mLastTouchDownTime = ev.getDownTime();  
  212.                                 mLastTouchDownIndex = childIndex;  
  213.                                 mLastTouchDownX = ev.getX();  
  214.                                 mLastTouchDownY = ev.getY();  
  215.                                 newTouchTarget = addTouchTarget(child, idBitsToAssign);  
  216.                                 alreadyDispatchedToNewTouchTarget = true;  
  217.                                 break;  
  218.                             }  
  219.                         }  
  220.                     }  
  221.   
  222.                       
  223.                     /** 
  224.                      * 该if条件表示: 
  225.                      * 经过前面的for循环没有找到子View接收Touch事件并且之前的mFirstTouchTarget不为空 
  226.                      */  
  227.                     if (newTouchTarget == null && mFirstTouchTarget != null) {  
  228.                         // Did not find a child to receive the event.  
  229.                         // Assign the pointer to the least recently added target.  
  230.                         newTouchTarget = mFirstTouchTarget;  
  231.                         while (newTouchTarget.next != null) {  
  232.                             newTouchTarget = newTouchTarget.next;  
  233.                         }  
  234.                         //newTouchTarget指向了最初的TouchTarget  
  235.                         newTouchTarget.pointerIdBits |= idBitsToAssign;  
  236.                     }  
  237.                 }  
  238.             }  
  239.   
  240.               
  241.               
  242.             /** 
  243.              * 分发Touch事件至target(Dispatch to touch targets) 
  244.              *  
  245.              * 经过上面对于ACTION_DOWN的处理后mFirstTouchTarget有两种情况: 
  246.              * 1 mFirstTouchTarget为null 
  247.              * 2 mFirstTouchTarget不为null 
  248.              *  
  249.              * 当然如果不是ACTION_DOWN就不会经过上面较繁琐的流程 
  250.              * 而是从此处开始执行,比如ACTION_MOVE和ACTION_UP 
  251.              */  
  252.             if (mFirstTouchTarget == null) {  
  253.                 /** 
  254.                  * 情况1:mFirstTouchTarget为null 
  255.                  *  
  256.                  * 经过上面的分析mFirstTouchTarget为null就是说Touch事件未被消费. 
  257.                  * 即没有找到能够消费touch事件的子组件或Touch事件被拦截了, 
  258.                  * 则调用ViewGroup的dispatchTransformedTouchEvent()方法处理Touch事件则和普通View一样. 
  259.                  * 即子View没有消费Touch事件,那么子View的上层ViewGroup才会调用其onTouchEvent()处理Touch事件. 
  260.                  * 在源码中的注释为:No touch targets so treat this as an ordinary view. 
  261.                  * 也就是说此时ViewGroup像一个普通的View那样调用dispatchTouchEvent(),且在dispatchTouchEvent() 
  262.                  * 中会去调用onTouchEvent()方法. 
  263.                  * 具体的说就是在调用dispatchTransformedTouchEvent()时第三个参数为null. 
  264.                  * 第三个参数View child为null会做什么样的处理呢? 
  265.                  * 请参见下面dispatchTransformedTouchEvent()的源码分析 
  266.                  *  
  267.                  * 这就是为什么子view对于Touch事件处理返回true那么其上层的ViewGroup就无法处理Touch事件了!!!!!!!!!! 
  268.                  * 这就是为什么子view对于Touch事件处理返回false那么其上层的ViewGroup才可以处理Touch事件!!!!!!!!!! 
  269.                  *  
  270.                  */  
  271.                 handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);  
  272.             } else {  
  273.                 /** 
  274.                  * 情况2:mFirstTouchTarget不为null即找到了可以消费Touch事件的子View且后续Touch事件可以传递到该子View 
  275.                  * 在源码中的注释为: 
  276.                  * Dispatch to touch targets, excluding the new touch target if we already dispatched to it.   
  277.                  * Cancel touch targets if necessary. 
  278.                  */  
  279.                 TouchTarget predecessor = null;  
  280.                 TouchTarget target = mFirstTouchTarget;  
  281.                 while (target != null) {  
  282.                     final TouchTarget next = target.next;  
  283.                     if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {  
  284.                         handled = true;  
  285.                     } else {  
  286.                         final boolean cancelChild = resetCancelNextUpFlag(target.child) || intercepted;  
  287.                         //对于非ACTION_DOWN事件继续传递给目标子组件进行处理,依然是递归调用dispatchTransformedTouchEvent()  
  288.                         if (dispatchTransformedTouchEvent(ev, cancelChild, target.child, target.pointerIdBits)) {  
  289.                             handled = true;  
  290.                         }  
  291.                         if (cancelChild) {  
  292.                             if (predecessor == null) {  
  293.                                 mFirstTouchTarget = next;  
  294.                             } else {  
  295.                                 predecessor.next = next;  
  296.                             }  
  297.                             target.recycle();  
  298.                             target = next;  
  299.                             continue;  
  300.                         }  
  301.                     }  
  302.                     predecessor = target;  
  303.                     target = next;  
  304.                 }  
  305.             }  
  306.   
  307.             /** 
  308.              * 处理ACTION_UP和ACTION_CANCEL 
  309.              * Update list of touch targets for pointer up or cancel, if needed. 
  310.              * 在此主要的操作是还原状态 
  311.              */  
  312.             if (canceled|| actionMasked == MotionEvent.ACTION_UP  
  313.                         || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  314.                 resetTouchState();  
  315.             } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {  
  316.                 final int actionIndex = ev.getActionIndex();  
  317.                 final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);  
  318.                 removePointersFromTouchTargets(idBitsToRemove);  
  319.             }  
  320.         }  
  321.   
  322.         if (!handled && mInputEventConsistencyVerifier != null) {  
  323.             mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);  
  324.         }  
  325.         return handled;  
  326.     }  
  327.       
  328.       
  329.       
  330.     //=====================以上为dispatchTouchEvent()源码分析======================  
  331.       
  332.       
  333.       
  334.     //===============以下为dispatchTransformedTouchEvent()源码分析=================  
  335.       
  336.     /** 
  337.      * 在dispatchTouchEvent()中调用dispatchTransformedTouchEvent()将事件分发给子View处理 
  338.      *  
  339.      * Transforms a motion event into the coordinate space of a particular child view, 
  340.      * filters out irrelevant pointer ids, and overrides its action if necessary. 
  341.      * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 
  342.      *  
  343.      * 在此请着重注意第三个参数:View child 
  344.      * 在dispatchTouchEvent()中多次调用了dispatchTransformedTouchEvent(),但是有时候第三个参数为null,有时又不是. 
  345.      * 那么这个参数是否为null有什么区别呢? 
  346.      * 在如下dispatchTransformedTouchEvent()源码中可见多次对于child是否为null的判断,并且均做出如下类似的操作: 
  347.      * if (child == null) { 
  348.      *       handled = super.dispatchTouchEvent(event); 
  349.      *    } else { 
  350.      *       handled = child.dispatchTouchEvent(event); 
  351.      * } 
  352.      * 这个代码是什么意思呢?? 
  353.      * 当child == null时会将Touch事件传递给该ViewGroup自身的dispatchTouchEvent()处理. 
  354.      * 即super.dispatchTouchEvent(event)正如源码中的注释描述的一样: 
  355.      * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 
  356.      * 当child != null时会调用该子view(当然该view可能是一个View也可能是一个ViewGroup)的dispatchTouchEvent(event)处理. 
  357.      * 即child.dispatchTouchEvent(event); 
  358.      *  
  359.      *  
  360.      */  
  361.     private boolean dispatchTransformedTouchEvent(MotionEvent event,boolean cancel,View child,int desiredPointerIdBits) {  
  362.         final boolean handled;  
  363.   
  364.         // Canceling motions is a special case.  We don't need to perform any transformations  
  365.         // or filtering.  The important part is the action, not the contents.  
  366.         final int oldAction = event.getAction();  
  367.         if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {  
  368.             event.setAction(MotionEvent.ACTION_CANCEL);  
  369.             if (child == null) {  
  370.                 handled = super.dispatchTouchEvent(event);  
  371.             } else {  
  372.                 handled = child.dispatchTouchEvent(event);  
  373.             }  
  374.             event.setAction(oldAction);  
  375.             return handled;  
  376.         }  
  377.   
  378.         // Calculate the number of pointers to deliver.  
  379.         final int oldPointerIdBits = event.getPointerIdBits();  
  380.         final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;  
  381.   
  382.         // If for some reason we ended up in an inconsistent state where it looks like we  
  383.         // might produce a motion event with no pointers in it, then drop the event.  
  384.         if (newPointerIdBits == 0) {  
  385.             return false;  
  386.         }  
  387.   
  388.         // If the number of pointers is the same and we don't need to perform any fancy  
  389.         // irreversible transformations, then we can reuse the motion event for this  
  390.         // dispatch as long as we are careful to revert any changes we make.  
  391.         // Otherwise we need to make a copy.  
  392.         final MotionEvent transformedEvent;  
  393.         if (newPointerIdBits == oldPointerIdBits) {  
  394.             if (child == null || child.hasIdentityMatrix()) {  
  395.                 if (child == null) {  
  396.                     handled = super.dispatchTouchEvent(event);  
  397.                 } else {  
  398.                     final float offsetX = mScrollX - child.mLeft;  
  399.                     final float offsetY = mScrollY - child.mTop;  
  400.                     event.offsetLocation(offsetX, offsetY);  
  401.   
  402.                     handled = child.dispatchTouchEvent(event);  
  403.   
  404.                     event.offsetLocation(-offsetX, -offsetY);  
  405.                 }  
  406.                 return handled;  
  407.             }  
  408.             transformedEvent = MotionEvent.obtain(event);  
  409.         } else {  
  410.             transformedEvent = event.split(newPointerIdBits);  
  411.         }  
  412.   
  413.         // Perform any necessary transformations and dispatch.  
  414.         if (child == null) {  
  415.             handled = super.dispatchTouchEvent(transformedEvent);  
  416.         } else {  
  417.             final float offsetX = mScrollX - child.mLeft;  
  418.             final float offsetY = mScrollY - child.mTop;  
  419.             transformedEvent.offsetLocation(offsetX, offsetY);  
  420.             if (! child.hasIdentityMatrix()) {  
  421.                 transformedEvent.transform(child.getInverseMatrix());  
  422.             }  
  423.   
  424.             handled = child.dispatchTouchEvent(transformedEvent);  
  425.         }  
  426.   
  427.         // Done.  
  428.         transformedEvent.recycle();  
  429.         return handled;  
  430.     }  
  431.       
  432.       
  433.       
  434.       
  435.       
  436.       
  437.   
  438. }  
package cc.aa;

import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;

public class UnderstandDispatchTouchEvent {
    /**
     * dispatchTouchEvent()源码学习及其注释
     * 常说事件传递中的流程是:dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent
     * 在这个链条中dispatchTouchEvent()是处在链首的位置当然也是最重要的.
     * 在dispatchTouchEvent()决定了Touch事件是由自己的onTouchEvent()处理
     * 还是分发给子View处理让子View调用其自身的dispatchTouchEvent()处理.
     * 
     * 
     * 其实dispatchTouchEvent()和onInterceptTouchEvent()以及onTouchEvent()的关系
     * 在dispatchTouchEvent()方法的源码中体现得很明显.
     * 比如dispatchTouchEvent()会调用onInterceptTouchEvent()来判断是否要拦截.
     * 比如dispatchTouchEvent()会调用dispatchTransformedTouchEvent()方法且在该方法中递归调用
     * dispatchTouchEvent();从而会在dispatchTouchEvent()里最终调用到onTouchEvent()
     * 
     * 
     * 
     * 重点关注:
     * 1 子View对于ACTION_DOWN的处理十分重要!!!!!
     *   ACTION_DOWN是一系列Touch事件的开端,如果子View对于该ACTION_DOWN事件在onTouchEvent()中返回了false即未消费.
     *   那么ViewGroup就不会把后续的ACTION_MOVE和ACTION_UP派发给该子View.在这种情况下ViewGroup就和普通的View一样了,
     *   调用该ViewGroup自己的dispatchTouchEvent()从而调用自己的onTouchEvent();即不会将事件分发给子View.
     *   详细代码请参见如下代码分析.
     *   
     * 2 为什么子view对于Touch事件处理返回true那么其上层的ViewGroup就无法处理Touch事件了?????
     *   这个想必大家都知道了,因为该Touch事件被子View消费了其上层的ViewGroup就无法处理该Touch事件了.
     *   那么在源码中的依据是什么呢??请看下面的源码分析
     *   
     * 参考资料:
     * 0 http://blog.csdn.net/sahadev_/article/details/23839039
     * 1 http://www.cnblogs.com/xiaoweiz/p/3838682.html
     * 2 http://hukai.me/android-deeper-touch-event-dispatch-process/
     * 3 http://blog.csdn.net/hdxiaoyu2/article/details/25563453
     * 4 http://www.eoeandroid.com/thread-542296-1-1.html
     * 5 http://www.eoeandroid.com/forum.php?mod=viewthread&tid=319301
     * 6 http://stackvoid.com/details-dispatch-onTouch-Event-in-Android/
     *   Thank you very much
     */
	
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            /**
             * 第一步:对于ACTION_DOWN进行处理(Handle an initial down)
             * 因为ACTION_DOWN是一系列事件的开端,当是ACTION_DOWN时进行一些初始化操作.
             * 从源码的注释也可以看出来:清除以往的Touch状态(state)开始新的手势(gesture)
             * cancelAndClearTouchTargets(ev)中有一个非常重要的操作:
             * 将mFirstTouchTarget设置为null!!!!
             * 随后在resetTouchState()中重置Touch状态标识
             */
            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)
			 * 在dispatchTouchEvent(MotionEventev)这段代码中
			 * 使用变量intercepted来标记ViewGroup是否拦截Touch事件的传递.
			 * 该变量在后续代码中起着很重要的作用.
			 */
            final boolean intercepted;
			// 事件为ACTION_DOWN或者mFirstTouchTarget不为null(即已经找到能够接收touch事件的目标组件)时if成立
            if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
            	//判断disallowIntercept(禁止拦截)标志位
				//因为在其他地方可能调用了requestDisallowInterceptTouchEvent(boolean disallowIntercept)
				//从而禁止执行是否需要拦截的判断(有点拗口~其实看requestDisallowInterceptTouchEvent()方法名就可明白)
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                //当没有禁止拦截判断时(即disallowIntercept为false)调用onInterceptTouchEvent(ev)方法
                if (!disallowIntercept) {
                	//既然disallowIntercept为false那么就调用onInterceptTouchEvent()方法将结果赋值给intercepted
                	//常说事件传递中的流程是:dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent
                	//其实在这就是一个体现,在dispatchTouchEvent()中调用了onInterceptTouchEvent()
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                	 //当禁止拦截判断时(即disallowIntercept为true)设置intercepted = false
                    intercepted = false;
                }
            } else {
            	//当事件不是ACTION_DOWN并且mFirstTouchTarget为null(即没有Touch的目标组件)时
            	//设置 intercepted = true表示ViewGroup执行Touch事件拦截的操作。
                //There are no touch targets and this action is not an initial down
                //so this view group continues to intercept touches.
                intercepted = true;
            }

            
            /**
             * 第三步:检查cancel(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;
            //不是ACTION_CANCEL并且ViewGroup的拦截标志位intercepted为false(不拦截)
            if (!canceled && !intercepted) {
            	//处理ACTION_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 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 (childrenCount != 0) {
                    	// 依据Touch坐标寻找子View来接收Touch事件
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final View[] children = mChildren;
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);

                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        // 遍历子View判断哪个子View接受Touch事件
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
                            final View child = children[childIndex];
                            if (!canViewReceivePointerEvents(child) || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                            	// 找到接收Touch事件的子View!!!!!!!即为newTouchTarget.
                            	// 既然已经找到了,所以执行break跳出for循环
                                // 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不满足,当然也不会执行break语句.
                             * 于是代码会执行到这里来.
                             * 
                             * 调用方法dispatchTransformedTouchEvent()将Touch事件传递给子View做
                             * 递归处理(也就是遍历该子View的View树)
                             * 该方法很重要,看一下源码中关于该方法的描述:
                             * 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.
                             * 将Touch事件传递给特定的子View.
                             * 该方法十分重要!!!!在该方法中为一个递归调用,会递归调用dispatchTouchEvent()方法!!!!!!!!!!!!!!
                             * 在dispatchTouchEvent()中:
                             * 如果子View为ViewGroup并且Touch没有被拦截那么递归调用dispatchTouchEvent()
                             * 如果子View为View那么就会调用其onTouchEvent(),这个就不再赘述了.
                             * 
                             * 
                             * 该方法返回true则表示子View消费掉该事件,同时进入该if判断.
                             * 满足if语句后重要的操作有:
                             * 1 给newTouchTarget赋值
                             * 2 给alreadyDispatchedToNewTouchTarget赋值为true.
                             *   看这个比较长的英语名字也可知其含义:已经将Touch派发给新的TouchTarget
                             * 3 执行break.
                             *   因为该for循环遍历子View判断哪个子View接受Touch事件,既然已经找到了
                             *   那么就跳出该for循环.
                             * 4 注意:
                             *   如果dispatchTransformedTouchEvent()返回false即子View
                             *   的onTouchEvent返回false(即Touch事件未被消费)那么就不满足该if条件,也就无法执行addTouchTarget()
                             *   从而导致mFirstTouchTarget为null.那么该子View就无法继续处理ACTION_MOVE事件
                             *   和ACTION_UP事件!!!!!!!!!!!!!!!!!!!!!!
                             * 5 注意:
                             *   如果dispatchTransformedTouchEvent()返回true即子View
                             *   的onTouchEvent返回true(即Touch事件被消费)那么就满足该if条件.
                             *   从而mFirstTouchTarget不为null!!!!!!!!!!!!!!!!!!!
                             * 6 小结:
                             *   对于此处ACTION_DOWN的处理具体体现在dispatchTransformedTouchEvent()
                             *   该方法返回boolean,如下:
                             *   true---->事件被消费----->mFirstTouchTarget!=null
                             *   false--->事件未被消费---->mFirstTouchTarget==null
                             *   因为在dispatchTransformedTouchEvent()会调用递归调用dispatchTouchEvent()和onTouchEvent()
                             *   所以dispatchTransformedTouchEvent()的返回值实际上是由onTouchEvent()决定的.
                             *   简单地说onTouchEvent()是否消费了Touch事件(true or false)的返回值决定了dispatchTransformedTouchEvent()
                             *   的返回值!!!!!!!!!!!!!从而决定了mFirstTouchTarget是否为null!!!!!!!!!!!!!!!!从而进一步决定了ViewGroup是否
                             *   处理Touch事件.这一点在下面的代码中很有体现.
                             *   
                             * 
                             */
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                mLastTouchDownIndex = childIndex;
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                        }
                    }

                    
                    /**
                     * 该if条件表示:
                     * 经过前面的for循环没有找到子View接收Touch事件并且之前的mFirstTouchTarget不为空
                     */
                    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指向了最初的TouchTarget
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            
            
            /**
             * 分发Touch事件至target(Dispatch to touch targets)
             * 
             * 经过上面对于ACTION_DOWN的处理后mFirstTouchTarget有两种情况:
             * 1 mFirstTouchTarget为null
             * 2 mFirstTouchTarget不为null
             * 
             * 当然如果不是ACTION_DOWN就不会经过上面较繁琐的流程
             * 而是从此处开始执行,比如ACTION_MOVE和ACTION_UP
             */
            if (mFirstTouchTarget == null) {
            	/**
            	 * 情况1:mFirstTouchTarget为null
            	 * 
            	 * 经过上面的分析mFirstTouchTarget为null就是说Touch事件未被消费.
            	 * 即没有找到能够消费touch事件的子组件或Touch事件被拦截了,
            	 * 则调用ViewGroup的dispatchTransformedTouchEvent()方法处理Touch事件则和普通View一样.
            	 * 即子View没有消费Touch事件,那么子View的上层ViewGroup才会调用其onTouchEvent()处理Touch事件.
            	 * 在源码中的注释为:No touch targets so treat this as an ordinary view.
            	 * 也就是说此时ViewGroup像一个普通的View那样调用dispatchTouchEvent(),且在dispatchTouchEvent()
            	 * 中会去调用onTouchEvent()方法.
            	 * 具体的说就是在调用dispatchTransformedTouchEvent()时第三个参数为null.
            	 * 第三个参数View child为null会做什么样的处理呢?
            	 * 请参见下面dispatchTransformedTouchEvent()的源码分析
            	 * 
            	 * 这就是为什么子view对于Touch事件处理返回true那么其上层的ViewGroup就无法处理Touch事件了!!!!!!!!!!
            	 * 这就是为什么子view对于Touch事件处理返回false那么其上层的ViewGroup才可以处理Touch事件!!!!!!!!!!
            	 * 
            	 */
                handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);
            } else {
            	/**
            	 * 情况2:mFirstTouchTarget不为null即找到了可以消费Touch事件的子View且后续Touch事件可以传递到该子View
            	 * 在源码中的注释为:
            	 * 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;
                        //对于非ACTION_DOWN事件继续传递给目标子组件进行处理,依然是递归调用dispatchTransformedTouchEvent()
                        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;
                }
            }

            /**
             * 处理ACTION_UP和ACTION_CANCEL
             * 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;
    }
    
    
    
    //=====================以上为dispatchTouchEvent()源码分析======================
    
    
    
    //===============以下为dispatchTransformedTouchEvent()源码分析=================
    
    /**
     * 在dispatchTouchEvent()中调用dispatchTransformedTouchEvent()将事件分发给子View处理
     * 
     * 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.
     * 
     * 在此请着重注意第三个参数:View child
     * 在dispatchTouchEvent()中多次调用了dispatchTransformedTouchEvent(),但是有时候第三个参数为null,有时又不是.
     * 那么这个参数是否为null有什么区别呢?
     * 在如下dispatchTransformedTouchEvent()源码中可见多次对于child是否为null的判断,并且均做出如下类似的操作:
     * if (child == null) {
     *       handled = super.dispatchTouchEvent(event);
     *    } else {
     *       handled = child.dispatchTouchEvent(event);
     * }
     * 这个代码是什么意思呢??
     * 当child == null时会将Touch事件传递给该ViewGroup自身的dispatchTouchEvent()处理.
     * 即super.dispatchTouchEvent(event)正如源码中的注释描述的一样:
     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
     * 当child != null时会调用该子view(当然该view可能是一个View也可能是一个ViewGroup)的dispatchTouchEvent(event)处理.
     * 即child.dispatchTouchEvent(event);
     * 
     * 
     */
    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;
    }
    
    
    
    
    
    

}

1
0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
城市应急指挥系统是智慧城市建设的重要组成部分,旨在提高城市对突发事件的预防和处置能力。系统背景源于自然灾害和事故灾难频发,如汶川地震和日本大地震等,这些事件造成了巨大的人员伤亡和财产损失。随着城市化进程的加快,应急信息化建设面临信息资源分散、管理标准不统一等问题,需要通过统筹管理和技术创新来解决。 系统的设计思路是通过先进的技术手段,如物联网、射频识别、卫星定位等,构建一个具有强大信息感知和通信能力的网络和平台。这将促进不同部门和层次之间的信息共享、交流和整合,提高城市资源的利用效率,满足城市对各种信息的获取和使用需求。在“十二五”期间,应急信息化工作将依托这些技术,实现动态监控、风险管理、预警以及统一指挥调度。 应急指挥系统的建设目标是实现快速有效的应对各种突发事件,保障人民生命财产安全,减少社会危害和经济损失。系统将包括预测预警、模拟演练、辅助决策、态势分析等功能,以及应急值守、预案管理、GIS应用等基本应用。此外,还包括支撑平台的建设,如接警中心、视频会议、统一通信等基础设施。 系统的实施将涉及到应急网络建设、应急指挥、视频监控、卫星通信等多个方面。通过高度集成的系统,建立统一的信息接收和处理平台,实现多渠道接入和融合指挥调度。此外,还包括应急指挥中心基础平台建设、固定和移动应急指挥通信系统建设,以及应急队伍建设,确保能够迅速响应并有效处置各类突发事件。 项目的意义在于,它不仅是提升灾害监测预报水平和预警能力的重要科技支撑,也是实现预防和减轻重大灾害和事故损失的关键。通过实施城市应急指挥系统,可以加强社会管理和公共服务,构建和谐社会,为打造平安城市提供坚实的基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值