• Android源码分析-点击事件派发机制


    转载请注明出处:http://blog.csdn.net/singwhatiwanna/article/details/17339857

    概述

    一直想写篇关于Android事件派发机制的文章,却一直没写,这两天刚好是周末,有时间了,想想写一篇吧,不然总是只停留在会用的层次上但是无法了解其内部机制。我用的是4.4源码,打开看看,挺复杂的,尤其是事件是怎么从Activity派发出来的,太费解了。了解Windows消息机制的人会发现,觉得Android的事件派发机制和Windows的消息派发机制挺像的,其实这是一种典型的消息“冒泡”机制,很多平台采用这个机制,消息最先到达最底层View,然后它先进行判断是不是它所需要的,否则就将消息传递给它的子View,这样一来,消息就从水底的气泡一样向上浮了一点距离,以此类推,气泡达到顶部和空气接触,破了(消息被处理了),当然也有气泡浮出到顶层了,还没破(消息无人处理),这个消息将由系统来处理,对于Android来说,会由Activity来处理。

    Android点击事件的派发机制

    1. 从Activity传递到底层View

    点击事件用MotionEvent来表示,当一个点击操作发生时,事件最先传递给当前Activity,由Activity的dispatchTouchEvent来进行事件派发,具体的工作是由Activity内部的Window来完成的,Window会将事件传递给decor view,decor view一般就是当前界面的底层容器(即setContentView所设置的View),通过Activity.getWindow.getDecorView()可以获得。另外,看下面代码的的时候,主要看我注释的地方,代码很多很复杂,我无法一一说明,但是我注释的地方都是关键点,是博主仔细读代码总结出来的。

    源码解读:

    事件是由哪里传递给Activity的,这个我还不清楚,但是不要紧,我们从activity开始分析,已经足够我们了解它的内部实现了。

    Code:Activity#dispatchTouchEvent

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. /** 
    2.  * Called to process touch screen events.  You can override this to 
    3.  * intercept all touch screen events before they are dispatched to the 
    4.  * window.  Be sure to call this implementation for touch screen events 
    5.  * that should be handled normally. 
    6.  *  
    7.  * @param ev The touch screen event. 
    8.  *  
    9.  * @return boolean Return true if this event was consumed. 
    10.  */  
    11. public boolean dispatchTouchEvent(MotionEvent ev) {  
    12.     if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
    13.         //这个函数其实是个空函数,啥也没干,如果你没重写的话,不用关心  
    14.         onUserInteraction();  
    15.     }  
    16.     //这里事件开始交给Activity所附属的Window进行派发,如果返回true,整个事件循环就结束了  
    17.     //返回false意味着事件没人处理,所有人的onTouchEvent都返回了false,那么Activity就要来做最后的收场。  
    18.     if (getWindow().superDispatchTouchEvent(ev)) {  
    19.         return true;  
    20.     }  
    21.     //这里,Activity来收场了,Activity的onTouchEvent被调用  
    22.     return onTouchEvent(ev);  
    23. }  

    Window是如何将事件传递给ViewGroup的

    Code:Window#superDispatchTouchEvent

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. /** 
    2.  * Used by custom windows, such as Dialog, to pass the touch screen event 
    3.  * further down the view hierarchy. Application developers should 
    4.  * not need to implement or call this. 
    5.  * 
    6.  */  
    7. public abstract boolean superDispatchTouchEvent(MotionEvent event);  
    这竟然是一个抽象函数,还注明了应用开发者不要实现它或者调用它,这是什么情况?再看看如下类的说明,大意是说:这个类可以控制顶级View的外观和行为策略,而且还说这个类的唯一一个实现位于android.policy.PhoneWindow,当你要实例化这个Window类的时候,你并不知道它的细节,因为这个类会被重构,只有一个工厂方法可以使用。好吧,还是很模糊啊,不太懂,不过我们可以看一下android.policy.PhoneWindow这个类,尽管实例化的时候此类会被重构,但是重构而已,功能是类似的。

    Abstract base class for a top-level window look and behavior policy. An instance of this class should be used as the top-level view added to the window manager. It provides standard UI policies such as a background, title area, default key processing, etc.

    The only existing implementation of this abstract class is android.policy.PhoneWindow, which you should instantiate when needing a Window. Eventually that class will be refactored and a factory method added for creating Window instances without knowing about a particular implementation. 

    Code:PhoneWindow#superDispatchTouchEvent
    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. @Override  
    2. public boolean superDispatchTouchEvent(MotionEvent event) {  
    3.     return mDecor.superDispatchTouchEvent(event);  
    4. }  
    这个逻辑很清晰了,PhoneWindow将事件传递给DecorView了,这个DecorView是啥呢,请看下面

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. private final class DecorView extends FrameLayout implements RootViewSurfaceTaker  
    2.   
    3. // This is the top-level view of the window, containing the window decor.  
    4. private DecorView mDecor;  
    5.   
    6. @Override  
    7. public final View getDecorView() {  
    8.     if (mDecor == null) {  
    9.         installDecor();  
    10.     }  
    11.     return mDecor;  
    12. }  

    顺便说一下,平时Window用的最多的就是((ViewGroup)getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0)即通过Activity来得到内部的View。这个mDecor显然就是getWindow().getDecorView()返回的View,而我们通过setContentView设置的View是它的一个子View。目前事件传递到了DecorView 这里,由于DecorView 继承自FrameLayout且是我们的父View,所以最终事件会传递给我们的View,原因先不管了,换句话来说,事件肯定会传递到我们的View,不然我们的应用如何响应点击事件呢。不过这不是我们的重点,重点是事件到了我们的View以后应该如何传递,这是对我们更有用的。从这里开始,事件已经传递到我们的顶级View了,注意:顶级View实际上是最底层View,也叫根View。

    2.底层View对事件的分发过程

    点击事件到底层View(一般是一个ViewGroup)以后,会调用ViewGroup的dispatchTouchEvent方法,然后的逻辑是这样的:如果底层ViewGroup拦截事件即onInterceptTouchEvent返回true,则事件由ViewGroup处理,这个时候,如果ViewGroup的mOnTouchListener被设置,则会onTouch会被调用,否则,onTouchEvent会被调用,也就是说,如果都提供的话,onTouch会屏蔽掉onTouchEvent。在onTouchEvent中,如果设置了mOnClickListener,则onClick会被调用。如果顶层ViewGroup不拦截事件,则事件会传递给它的在点击事件链上的子View,这个时候,子View的dispatchTouchEvent会被调用,到此为止,事件已经从最底层View传递给了上一层View,接下来的行为和其底层View一致,如此循环,完成整个事件派发。另外要说明的是,ViewGroup默认是不拦截点击事件的,其onInterceptTouchEvent返回false。

    源码解读:

    Code:ViewGroup#dispatchTouchEvent

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. @Override  
    2. public boolean dispatchTouchEvent(MotionEvent ev) {  
    3.     if (mInputEventConsistencyVerifier != null) {  
    4.         mInputEventConsistencyVerifier.onTouchEvent(ev, 1);  
    5.     }  
    6.   
    7.     boolean handled = false;  
    8.     if (onFilterTouchEventForSecurity(ev)) {  
    9.         final int action = ev.getAction();  
    10.         final int actionMasked = action & MotionEvent.ACTION_MASK;  
    11.   
    12.         // Handle an initial down.  
    13.         if (actionMasked == MotionEvent.ACTION_DOWN) {  
    14.             // Throw away all previous state when starting a new touch gesture.  
    15.             // The framework may have dropped the up or cancel event for the previous gesture  
    16.             // due to an app switch, ANR, or some other state change.  
    17.             cancelAndClearTouchTargets(ev);  
    18.             resetTouchState();  
    19.         }  
    20.   
    21.         // Check for interception.  
    22.         final boolean intercepted;  
    23.         if (actionMasked == MotionEvent.ACTION_DOWN  
    24.                 || mFirstTouchTarget != null) {  
    25.             final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
    26.             if (!disallowIntercept) {  
    27.           //这里判断是否拦截点击事件,如果拦截,则intercepted=true  
    28.                 intercepted = onInterceptTouchEvent(ev);  
    29.                 ev.setAction(action); // restore action in case it was changed  
    30.             } else {  
    31.                 intercepted = false;  
    32.             }  
    33.         } else {  
    34.             // There are no touch targets and this action is not an initial down  
    35.             // so this view group continues to intercept touches.  
    36.             intercepted = true;  
    37.         }  
    38.   
    39.         // Check for cancelation.  
    40.         final boolean canceled = resetCancelNextUpFlag(this)  
    41.                 || actionMasked == MotionEvent.ACTION_CANCEL;  
    42.   
    43.         // Update list of touch targets for pointer down, if needed.  
    44.         final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;  
    45.         TouchTarget newTouchTarget = null;  
    46.         boolean alreadyDispatchedToNewTouchTarget = false;  
    47.          //这里面一大堆是派发事件到子View,如果intercepted是true,则直接跳过  
    48.         if (!canceled && !intercepted) {  
    49.             if (actionMasked == MotionEvent.ACTION_DOWN  
    50.                     || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)  
    51.                     || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
    52.                 final int actionIndex = ev.getActionIndex(); // always 0 for down  
    53.                 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)  
    54.                         : TouchTarget.ALL_POINTER_IDS;  
    55.   
    56.                 // Clean up earlier touch targets for this pointer id in case they  
    57.                 // have become out of sync.  
    58.                 removePointersFromTouchTargets(idBitsToAssign);  
    59.   
    60.                 final int childrenCount = mChildrenCount;  
    61.                 if (newTouchTarget == null && childrenCount != 0) {  
    62.                     final float x = ev.getX(actionIndex);  
    63.                     final float y = ev.getY(actionIndex);  
    64.                     // Find a child that can receive the event.  
    65.                     // Scan children from front to back.  
    66.                     final View[] children = mChildren;  
    67.   
    68.                     final boolean customOrder = isChildrenDrawingOrderEnabled();  
    69.                     for (int i = childrenCount - 1; i >= 0; i--) {  
    70.                         final int childIndex = customOrder ?  
    71.                                 getChildDrawingOrder(childrenCount, i) : i;  
    72.                         final View child = children[childIndex];  
    73.                         if (!canViewReceivePointerEvents(child)  
    74.                                 || !isTransformedTouchPointInView(x, y, child, null)) {  
    75.                             continue;  
    76.                         }  
    77.   
    78.                         newTouchTarget = getTouchTarget(child);  
    79.                         if (newTouchTarget != null) {  
    80.                             // Child is already receiving touch within its bounds.  
    81.                             // Give it the new pointer in addition to the ones it is handling.  
    82.                             newTouchTarget.pointerIdBits |= idBitsToAssign;  
    83.                             break;  
    84.                         }  
    85.   
    86.                         resetCancelNextUpFlag(child);  
    87.                         if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {  
    88.                             // Child wants to receive touch within its bounds.  
    89.                             mLastTouchDownTime = ev.getDownTime();  
    90.                             mLastTouchDownIndex = childIndex;  
    91.                             mLastTouchDownX = ev.getX();  
    92.                             mLastTouchDownY = ev.getY();  
    93.                             //注意下面两句,如果有子View处理了点击事件,则newTouchTarget会被赋值,  
    94.                             //同时alreadyDispatchedToNewTouchTarget也会为true,这两个变量是直接影响下面的代码逻辑的。  
    95.                             newTouchTarget = addTouchTarget(child, idBitsToAssign);  
    96.                             alreadyDispatchedToNewTouchTarget = true;  
    97.                             break;  
    98.                         }  
    99.                     }  
    100.                 }  
    101.   
    102.                 if (newTouchTarget == null && mFirstTouchTarget != null) {  
    103.                     // Did not find a child to receive the event.  
    104.                     // Assign the pointer to the least recently added target.  
    105.                     newTouchTarget = mFirstTouchTarget;  
    106.                     while (newTouchTarget.next != null) {  
    107.                         newTouchTarget = newTouchTarget.next;  
    108.                     }  
    109.                     newTouchTarget.pointerIdBits |= idBitsToAssign;  
    110.                 }  
    111.             }  
    112.         }  
    113.   
    114.         // Dispatch to touch targets.  
    115.      //这里如果当前ViewGroup拦截了事件,或者其子View的onTouchEvent都返回了false,则事件会由ViewGroup处理  
    116.         if (mFirstTouchTarget == null) {  
    117.             // No touch targets so treat this as an ordinary view.  
    118.           //这里就是ViewGroup对点击事件的处理  
    119.             handled = dispatchTransformedTouchEvent(ev, canceled, null,  
    120.                     TouchTarget.ALL_POINTER_IDS);  
    121.         } else {  
    122.             // Dispatch to touch targets, excluding the new touch target if we already  
    123.             // dispatched to it.  Cancel touch targets if necessary.  
    124.             TouchTarget predecessor = null;  
    125.             TouchTarget target = mFirstTouchTarget;  
    126.             while (target != null) {  
    127.                 final TouchTarget next = target.next;  
    128.                 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {  
    129.                     handled = true;  
    130.                 } else {  
    131.                     final boolean cancelChild = resetCancelNextUpFlag(target.child)  
    132.                             || intercepted;  
    133.                     if (dispatchTransformedTouchEvent(ev, cancelChild,  
    134.                             target.child, target.pointerIdBits)) {  
    135.                         handled = true;  
    136.                     }  
    137.                     if (cancelChild) {  
    138.                         if (predecessor == null) {  
    139.                             mFirstTouchTarget = next;  
    140.                         } else {  
    141.                             predecessor.next = next;  
    142.                         }  
    143.                         target.recycle();  
    144.                         target = next;  
    145.                         continue;  
    146.                     }  
    147.                 }  
    148.                 predecessor = target;  
    149.                 target = next;  
    150.             }  
    151.         }  
    152.   
    153.         // Update list of touch targets for pointer up or cancel, if needed.  
    154.         if (canceled  
    155.                 || actionMasked == MotionEvent.ACTION_UP  
    156.                 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
    157.             resetTouchState();  
    158.         } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {  
    159.             final int actionIndex = ev.getActionIndex();  
    160.             final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);  
    161.             removePointersFromTouchTargets(idBitsToRemove);  
    162.         }  
    163.     }  
    164.   
    165.     if (!handled && mInputEventConsistencyVerifier != null) {  
    166.         mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);  
    167.     }  
    168.     return handled;  
    169. }  

    下面再看ViewGroup对点击事件的处理

    Code:ViewGroup#dispatchTransformedTouchEvent

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. /** 
    2.  * Transforms a motion event into the coordinate space of a particular child view, 
    3.  * filters out irrelevant pointer ids, and overrides its action if necessary. 
    4.  * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 
    5.  */  
    6. private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,  
    7.         View child, int desiredPointerIdBits) {  
    8.     final boolean handled;  
    9.   
    10.     // Canceling motions is a special case.  We don't need to perform any transformations  
    11.     // or filtering.  The important part is the action, not the contents.  
    12.     final int oldAction = event.getAction();  
    13.     if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {  
    14.         event.setAction(MotionEvent.ACTION_CANCEL);  
    15.         if (child == null) {  
    16.       //这里就是ViewGroup对点击事件的处理,其调用了View的dispatchTouchEvent方法  
    17.             handled = super.dispatchTouchEvent(event);  
    18.         } else {  
    19.             handled = child.dispatchTouchEvent(event);  
    20.         }  
    21.         event.setAction(oldAction);  
    22.         return handled;  
    23.     }  
    24.   
    25.     // Calculate the number of pointers to deliver.  
    26.     final int oldPointerIdBits = event.getPointerIdBits();  
    27.     final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;  
    28.   
    29.     // If for some reason we ended up in an inconsistent state where it looks like we  
    30.     // might produce a motion event with no pointers in it, then drop the event.  
    31.     if (newPointerIdBits == 0) {  
    32.         return false;  
    33.     }  
    34.   
    35.     // If the number of pointers is the same and we don't need to perform any fancy  
    36.     // irreversible transformations, then we can reuse the motion event for this  
    37.     // dispatch as long as we are careful to revert any changes we make.  
    38.     // Otherwise we need to make a copy.  
    39.     final MotionEvent transformedEvent;  
    40.     if (newPointerIdBits == oldPointerIdBits) {  
    41.         if (child == null || child.hasIdentityMatrix()) {  
    42.             if (child == null) {  
    43.                 handled = super.dispatchTouchEvent(event);  
    44.             } else {  
    45.                 final float offsetX = mScrollX - child.mLeft;  
    46.                 final float offsetY = mScrollY - child.mTop;  
    47.                 event.offsetLocation(offsetX, offsetY);  
    48.   
    49.                 handled = child.dispatchTouchEvent(event);  
    50.   
    51.                 event.offsetLocation(-offsetX, -offsetY);  
    52.             }  
    53.             return handled;  
    54.         }  
    55.         transformedEvent = MotionEvent.obtain(event);  
    56.     } else {  
    57.         transformedEvent = event.split(newPointerIdBits);  
    58.     }  
    59.   
    60.     // Perform any necessary transformations and dispatch.  
    61.     if (child == null) {  
    62.         handled = super.dispatchTouchEvent(transformedEvent);  
    63.     } else {  
    64.         final float offsetX = mScrollX - child.mLeft;  
    65.         final float offsetY = mScrollY - child.mTop;  
    66.         transformedEvent.offsetLocation(offsetX, offsetY);  
    67.         if (! child.hasIdentityMatrix()) {  
    68.             transformedEvent.transform(child.getInverseMatrix());  
    69.         }  
    70.   
    71.         handled = child.dispatchTouchEvent(transformedEvent);  
    72.     }  
    73.   
    74.     // Done.  
    75.     transformedEvent.recycle();  
    76.     return handled;  
    77. }  
    再看

    Code:View#dispatchTouchEvent

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
    1. /** 
    2.   * Pass the touch screen motion event down to the target view, or this 
    3.   * view if it is the target. 
    4.   * 
    5.   * @param event The motion event to be dispatched. 
    6.   * @return True if the event was handled by the view, false otherwise. 
    7.   */  
    8.  public boolean dispatchTouchEvent(MotionEvent event) {  
    9.      if (mInputEventConsistencyVerifier != null) {  
    10.          mInputEventConsistencyVerifier.onTouchEvent(event, 0);  
    11.      }  
    12.   
    13.      if (onFilterTouchEventForSecurity(event)) {  
    14.          //noinspection SimplifiableIfStatement  
    15.          ListenerInfo li = mListenerInfo;  
    16.          if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED  
    17.                  && li.mOnTouchListener.onTouch(this, event)) {  
    18.              return true;  
    19.          }  
    20.   
    21.          if (onTouchEvent(event)) {  
    22.              return true;  
    23.          }  
    24.      }  
    25.   
    26.      if (mInputEventConsistencyVerifier != null) {  
    27.          mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);  
    28.      }  
    29.      return false;  
    30.  }  
    这段代码比较简单,View对事件的处理是这样的:如果设置了OnTouchListener就调用onTouch,否则就直接调用onTouchEvent,而onClick是在onTouchEvent内部通过performClick触发的。简单来说,事件如果被ViewGroup拦截或者子View的onTouchEvent都返回了false,则事件最终由ViewGroup处理。

    3.无人处理的点击事件

    如果一个点击事件,子View的onTouchEvent返回了false,则父View的onTouchEvent会被直接调用,以此类推。如果所有的View都不处理,则最终会由Activity来处理,这个时候,Activity的onTouchEvent会被调用。这个问题已经在1和2中做了说明。

  • 相关阅读:
    模拟退火、禁忌搜索、迭代局部搜索求解TSP问题Python代码分享
    多起点的局部搜索算法(multi-start local search)解决TSP问题(附Java代码及注释)
    爬取一定范围内的地图兴趣点并生成地点分布图
    Tabu Search求解作业车间调度问题(Job Shop Scheduling)-附Java代码
    Python爬虫系列
    干货 | 蚁群算法求解带时间窗的车辆路径规划问题详解(附Java代码)
    10分钟教你Python爬虫(下)--爬虫的基本模块与简单的实战
    vs code 打开文件时,取消文件目录的自动定位跟踪
    eclipse自动补全导致变量会跟上String后缀的问题解决
    16. nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "auditUnitName"
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6469477.html
Copyright © 2020-2023  润新知