转载请注明出处: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
plain
copy

  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
plain
copy

  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
plain
copy

  1. @Override
  2. public boolean superDispatchTouchEvent(MotionEvent event) {
  3. return mDecor.superDispatchTouchEvent(event);
  4. }

这个逻辑很清晰了,PhoneWindow将事件传递给DecorView了,这个DecorView是啥呢,请看下面

[java] view
plain
copy

  1. private final class DecorView extends FrameLayout implements RootViewSurfaceTaker
  2. // This is the top-level view of the window, containing the window decor.
  3. private DecorView mDecor;
  4. @Override
  5. public final View getDecorView() {
  6. if (mDecor == null) {
  7. installDecor();
  8. }
  9. return mDecor;
  10. }

顺便说一下,平时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
plain
copy

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

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

Code:ViewGroup#dispatchTransformedTouchEvent

[java] view
plain
copy

  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. // Canceling motions is a special case.  We don't need to perform any transformations
  10. // or filtering.  The important part is the action, not the contents.
  11. final int oldAction = event.getAction();
  12. if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
  13. event.setAction(MotionEvent.ACTION_CANCEL);
  14. if (child == null) {
  15. //这里就是ViewGroup对点击事件的处理,其调用了View的dispatchTouchEvent方法
  16. handled = super.dispatchTouchEvent(event);
  17. } else {
  18. handled = child.dispatchTouchEvent(event);
  19. }
  20. event.setAction(oldAction);
  21. return handled;
  22. }
  23. // Calculate the number of pointers to deliver.
  24. final int oldPointerIdBits = event.getPointerIdBits();
  25. final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
  26. // If for some reason we ended up in an inconsistent state where it looks like we
  27. // might produce a motion event with no pointers in it, then drop the event.
  28. if (newPointerIdBits == 0) {
  29. return false;
  30. }
  31. // If the number of pointers is the same and we don't need to perform any fancy
  32. // irreversible transformations, then we can reuse the motion event for this
  33. // dispatch as long as we are careful to revert any changes we make.
  34. // Otherwise we need to make a copy.
  35. final MotionEvent transformedEvent;
  36. if (newPointerIdBits == oldPointerIdBits) {
  37. if (child == null || child.hasIdentityMatrix()) {
  38. if (child == null) {
  39. handled = super.dispatchTouchEvent(event);
  40. } else {
  41. final float offsetX = mScrollX - child.mLeft;
  42. final float offsetY = mScrollY - child.mTop;
  43. event.offsetLocation(offsetX, offsetY);
  44. handled = child.dispatchTouchEvent(event);
  45. event.offsetLocation(-offsetX, -offsetY);
  46. }
  47. return handled;
  48. }
  49. transformedEvent = MotionEvent.obtain(event);
  50. } else {
  51. transformedEvent = event.split(newPointerIdBits);
  52. }
  53. // Perform any necessary transformations and dispatch.
  54. if (child == null) {
  55. handled = super.dispatchTouchEvent(transformedEvent);
  56. } else {
  57. final float offsetX = mScrollX - child.mLeft;
  58. final float offsetY = mScrollY - child.mTop;
  59. transformedEvent.offsetLocation(offsetX, offsetY);
  60. if (! child.hasIdentityMatrix()) {
  61. transformedEvent.transform(child.getInverseMatrix());
  62. }
  63. handled = child.dispatchTouchEvent(transformedEvent);
  64. }
  65. // Done.
  66. transformedEvent.recycle();
  67. return handled;
  68. }

再看

Code:View#dispatchTouchEvent

[java] view
plain
copy

  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. if (onFilterTouchEventForSecurity(event)) {
  13. //noinspection SimplifiableIfStatement
  14. ListenerInfo li = mListenerInfo;
  15. if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
  16. && li.mOnTouchListener.onTouch(this, event)) {
  17. return true;
  18. }
  19. if (onTouchEvent(event)) {
  20. return true;
  21. }
  22. }
  23. if (mInputEventConsistencyVerifier != null) {
  24. mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
  25. }
  26. return false;
  27. }

这段代码比较简单,View对事件的处理是这样的:如果设置了OnTouchListener就调用onTouch,否则就直接调用onTouchEvent,而onClick是在onTouchEvent内部通过performClick触发的。简单来说,事件如果被ViewGroup拦截或者子View的onTouchEvent都返回了false,则事件最终由ViewGroup处理。

3.无人处理的点击事件

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

最新文章

  1. Xstream解析XML
  2. 【转】CwRsync简介
  3. 关于stacking context和CSS z-index的总结
  4. 列出man手册所有函数的方法
  5. GitHub进一步了解
  6. 理解C++11正则表达式(2)
  7. HDU 献给杭电五十周年校庆的礼物 1290 递推
  8. 判定生死的心跳机制 --ESFramework 4.0 快速上手(07)
  9. Freemaker配置文件详解
  10. javaEE-string家族三大流氓
  11. Canvas学习系列二:Canvas的坐标系统
  12. 解释型语言VS编译型语言
  13. [LeetCode] 22. 括号生成
  14. C#中get和set属性的作用
  15. puppeteer,新款headless chrome
  16. Java并发-懒汉式单例设计模式加volatile的原因
  17. 常用正则表达式:手机、电话、邮箱、身份证、IP地址、网址、日期等
  18. 使用RT3070使开发板上网
  19. get提交
  20. install ros-indigo-map-server

热门文章

  1. 当数据库没有备份,redo或undo损坏
  2. js里的表格数组某个key去重
  3. POJ 2386 Lake Counting DFS水水
  4. 异步载入JS
  5. Android滑动到顶部悬停
  6. 大话Spark(8)-源码之DAGScheduler
  7. arm-linux-gcc: Command not found
  8. mysql select 无order by 默认排序 出现乱序的问题
  9. minizlib
  10. iOS开发:枚举的介绍与使用