Android事件传递机制详解及最新源码分析——ViewGroup篇

版权声明:本文出自汪磊的博客,转载请务必注明出处。

在上一篇《Android事件传递机制详解及最新源码分析——View篇》中,详细讲解了View事件的传递机制,没掌握或者掌握不扎实的小伙伴,强烈建议先阅读上一篇。

好了,废话还是少说,直奔主题,开始本篇的ViewGroup事件传递机制探索之旅。

依然从简单的Demo例子现象开始分析

新建安卓工程,首先自定义一个Button以及一个RelativeLayout,很简单,只是重写了主要与事件传递机制相关的方法,代码如下:

自定义WLButton类:

 1 public class WLButton extends Button {
 2 
 3     private static final String TAG = "WL";
 4     
 5     public WLButton(Context context, AttributeSet attrs) {
 6         super(context, attrs);
 7     }
 8     
 9     @Override
10     public boolean dispatchTouchEvent(MotionEvent event) {
11         Log.i(TAG, "WLButton  dispatchTouchEvent : "+event.getAction());
12         return super.dispatchTouchEvent(event);
13     }
14     
15     @Override
16     public boolean onTouchEvent(MotionEvent event) {
17         Log.i(TAG, "WLButton  onTouchEvent : "+event.getAction());
18         return super.onTouchEvent(event);
19     }
20 
21 }

自定义WLRelativeLayout类:

 1 public class WLRelativeLayout extends RelativeLayout {
 2 
 3     private static final String TAG = "WL";
 4     
 5     public WLRelativeLayout(Context context, AttributeSet attrs) {
 6         super(context, attrs);
 7     }
 8     
 9     @Override
10     public boolean dispatchTouchEvent(MotionEvent ev) {
11         Log.i(TAG, "WLRelativeLayout  dispatchTouchEvent : "+ev.getAction());
12         return super.dispatchTouchEvent(ev);
13     }
14     
15     @Override
16     public boolean onInterceptTouchEvent(MotionEvent ev) {
17         Log.i(TAG, "WLRelativeLayout  onInterceptTouchEvent : "+ev.getAction());
18         return super.onInterceptTouchEvent(ev);
19     }
20     
21     @Override
22     public boolean onTouchEvent(MotionEvent event) {
23         Log.i(TAG, "WLRelativeLayout  onTouchEvent : "+event.getAction());
24         return super.onTouchEvent(event);
25     }
26 }

 对于WLRelativeLayout会额外注意到我们重写父类onInterceptTouchEvent方法,这里目前只是打印一下信息,追踪什么时候调用的,至于这个方法具体有什么作用先别着急,后续分析源码的时候咱们会着重分析。

接下来我们编写Acticity的代码,如下:

 1 public class MainActivity extends Activity implements OnTouchListener, OnClickListener {
 2 
 3     private static final String TAG = "WL";
 4     private Button mButton;
 5     private WLRelativeLayout myRelativeLayout;
 6     
 7     @Override
 8     protected void onCreate(Bundle savedInstanceState) {
 9         super.onCreate(savedInstanceState);
10         setContentView(R.layout.activity_main);
11         
12         mButton = (Button) findViewById(R.id.click);
13         mButton.setOnTouchListener(this);
14         mButton.setOnClickListener(this);
15         
16         myRelativeLayout = (WLRelativeLayout) findViewById(R.id.myRelativeLayout);
17         myRelativeLayout.setOnTouchListener(this);
18         myRelativeLayout.setOnClickListener(this);
19 
20     }
21 
22     @Override
23     public void onClick(View v) {
24         //
25         Log.i(TAG, "onClick :"+v);
26     }
27 
28     @Override
29     public boolean onTouch(View v, MotionEvent event) {
30         //
31         Log.i(TAG, "onTouch :"+",...action :"+event.getAction()+"...View :"+v);
32         return false;
33     }
34 
35 }

没什么好解释的,稍有经验的应该都能看懂,我们看下来不同操作打印信息:

首先我们正常点击Button,打印信息如下:

我们看到首先执行的是WLRelativeLayout的dispatchTouchEvent方法,然后执行onInterceptTouchEvent方法,接下来执行WLButton的dispatchTouchEvent方法,之后就不用多余解释了吧,就是上篇讲到的View的事件分发流程。

 

接下来,我们Button外部区域部分看看打印信息,如下:

点击外部区域有没有发现和View事件分发流程特别像,只不过多了一个onInterceptTouchEvent方法,但是我们发现在我们按下手指的时候(action为0的时候)会触发onInterceptTouchEvent方法,然而抬起手指的时候(action为1的时候)却没有触发onInterceptTouchEvent方法,这是为什么呢?别急,等我们分析完源码就会有答案。

我们注意到onInterceptTouchEvent 是有返回值的,默认我们是调用父类的onInterceptTouchEvent方法,那我们看看父类中onInterceptTouchEvent是什么逻辑呢,点进去看一下源码,我了个叉,真简单,如下:

1 public boolean onInterceptTouchEvent(MotionEvent ev) {
2       return false;
3 }

 就直接返回一个false,那好,我们人为在子类中返回true,然后点击button看看打印情况。

接下来我们在WLRelativeLayout中将onInterceptTouchEvent返回值设置为true,然后运行程序会发现点击button内外打印信息都如下:

是不是有种触摸或者点击事件和button没关系了的感觉,就WLRelativeLayout自己玩的样子,这又是为什么呢?好了,带着这样疑问我们查看一下源码,看看源码层是怎么处理的。

 ViewGroup事件传递机制源码分析(源码版本为API23

通过上面demo现象,我们得知,当我们点击Button首先触发的是WLRelativeLayout中的dispatchTouchEvent,我们向上寻找最终在ViewGroup中找到dispatchTouchEvent这个方法,我们知道ViewGroup是继承自View,不用过多解释了,ViewGroup只是将这个方法重写了而已。

ViewGroup中dispatchTouchEvent方法源码如下:

  1     @Override
  2     public boolean dispatchTouchEvent(MotionEvent ev) {
  3         if (mInputEventConsistencyVerifier != null) {
  4             mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
  5         }
  6 
  7         // If the event targets the accessibility focused view and this is it, start
  8         // normal event dispatch. Maybe a descendant is what will handle the click.
  9         if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
 10             ev.setTargetAccessibilityFocus(false);
 11         }
 12 
 13         boolean handled = false;
 14         if (onFilterTouchEventForSecurity(ev)) {
 15             final int action = ev.getAction();
 16             final int actionMasked = action & MotionEvent.ACTION_MASK;
 17 
 18             // Handle an initial down.
 19             if (actionMasked == MotionEvent.ACTION_DOWN) {
 20                 // Throw away all previous state when starting a new touch gesture.
 21                 // The framework may have dropped the up or cancel event for the previous gesture
 22                 // due to an app switch, ANR, or some other state change.
 23                 cancelAndClearTouchTargets(ev);
 24                 resetTouchState();
 25             }
 26 
 27             // Check for interception.
 28             final boolean intercepted;
 29             if (actionMasked == MotionEvent.ACTION_DOWN
 30                     || mFirstTouchTarget != null) {
 31                 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
 32                 if (!disallowIntercept) {
 33                     intercepted = onInterceptTouchEvent(ev);
 34                     ev.setAction(action); // restore action in case it was changed
 35                 } else {
 36                     intercepted = false;
 37                 }
 38             } else {
 39                 // There are no touch targets and this action is not an initial down
 40                 // so this view group continues to intercept touches.
 41                 intercepted = true;
 42             }
 43 
 44             // If intercepted, start normal event dispatch. Also if there is already
 45             // a view that is handling the gesture, do normal event dispatch.
 46             if (intercepted || mFirstTouchTarget != null) {
 47                 ev.setTargetAccessibilityFocus(false);
 48             }
 49 
 50             // Check for cancelation.
 51             final boolean canceled = resetCancelNextUpFlag(this)
 52                     || actionMasked == MotionEvent.ACTION_CANCEL;
 53 
 54             // Update list of touch targets for pointer down, if needed.
 55             final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
 56             TouchTarget newTouchTarget = null;
 57             boolean alreadyDispatchedToNewTouchTarget = false;
 58             if (!canceled && !intercepted) {
 59 
 60                 // If the event is targeting accessiiblity focus we give it to the
 61                 // view that has accessibility focus and if it does not handle it
 62                 // we clear the flag and dispatch the event to all children as usual.
 63                 // We are looking up the accessibility focused host to avoid keeping
 64                 // state since these events are very rare.
 65                 View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
 66                         ? findChildWithAccessibilityFocus() : null;
 67 
 68                 if (actionMasked == MotionEvent.ACTION_DOWN
 69                         || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
 70                         || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
 71                     final int actionIndex = ev.getActionIndex(); // always 0 for down
 72                     final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
 73                             : TouchTarget.ALL_POINTER_IDS;
 74 
 75                     // Clean up earlier touch targets for this pointer id in case they
 76                     // have become out of sync.
 77                     removePointersFromTouchTargets(idBitsToAssign);
 78 
 79                     final int childrenCount = mChildrenCount;
 80                     if (newTouchTarget == null && childrenCount != 0) {
 81                         final float x = ev.getX(actionIndex);
 82                         final float y = ev.getY(actionIndex);
 83                         // Find a child that can receive the event.
 84                         // Scan children from front to back.
 85                         final ArrayList<View> preorderedList = buildOrderedChildList();
 86                         final boolean customOrder = preorderedList == null
 87                                 && isChildrenDrawingOrderEnabled();
 88                         final View[] children = mChildren;
 89                         for (int i = childrenCount - 1; i >= 0; i--) {
 90                             final int childIndex = customOrder
 91                                     ? getChildDrawingOrder(childrenCount, i) : i;
 92                             final View child = (preorderedList == null)
 93                                     ? children[childIndex] : preorderedList.get(childIndex);
 94 
 95                             // If there is a view that has accessibility focus we want it
 96                             // to get the event first and if not handled we will perform a
 97                             // normal dispatch. We may do a double iteration but this is
 98                             // safer given the timeframe.
 99                             if (childWithAccessibilityFocus != null) {
100                                 if (childWithAccessibilityFocus != child) {
101                                     continue;
102                                 }
103                                 childWithAccessibilityFocus = null;
104                                 i = childrenCount - 1;
105                             }
106 
107                             if (!canViewReceivePointerEvents(child)
108                                     || !isTransformedTouchPointInView(x, y, child, null)) {
109                                 ev.setTargetAccessibilityFocus(false);
110                                 continue;
111                             }
112 
113                             newTouchTarget = getTouchTarget(child);
114                             if (newTouchTarget != null) {
115                                 // Child is already receiving touch within its bounds.
116                                 // Give it the new pointer in addition to the ones it is handling.
117                                 newTouchTarget.pointerIdBits |= idBitsToAssign;
118                                 break;
119                             }
120 
121                             resetCancelNextUpFlag(child);
122                             if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
123                                 // Child wants to receive touch within its bounds.
124                                 mLastTouchDownTime = ev.getDownTime();
125                                 if (preorderedList != null) {
126                                     // childIndex points into presorted list, find original index
127                                     for (int j = 0; j < childrenCount; j++) {
128                                         if (children[childIndex] == mChildren[j]) {
129                                             mLastTouchDownIndex = j;
130                                             break;
131                                         }
132                                     }
133                                 } else {
134                                     mLastTouchDownIndex = childIndex;
135                                 }
136                                 mLastTouchDownX = ev.getX();
137                                 mLastTouchDownY = ev.getY();
138                                 newTouchTarget = addTouchTarget(child, idBitsToAssign);
139                                 alreadyDispatchedToNewTouchTarget = true;
140                                 break;
141                             }
142 
143                             // The accessibility focus didn't handle the event, so clear
144                             // the flag and do a normal dispatch to all children.
145                             ev.setTargetAccessibilityFocus(false);
146                         }
147                         if (preorderedList != null) preorderedList.clear();
148                     }
149 
150                     if (newTouchTarget == null && mFirstTouchTarget != null) {
151                         // Did not find a child to receive the event.
152                         // Assign the pointer to the least recently added target.
153                         newTouchTarget = mFirstTouchTarget;
154                         while (newTouchTarget.next != null) {
155                             newTouchTarget = newTouchTarget.next;
156                         }
157                         newTouchTarget.pointerIdBits |= idBitsToAssign;
158                     }
159                 }
160             }
161 
162             // Dispatch to touch targets.
163             if (mFirstTouchTarget == null) {
164                 // No touch targets so treat this as an ordinary view.
165                 handled = dispatchTransformedTouchEvent(ev, canceled, null,
166                         TouchTarget.ALL_POINTER_IDS);
167             } else {
168                 // Dispatch to touch targets, excluding the new touch target if we already
169                 // dispatched to it.  Cancel touch targets if necessary.
170                 TouchTarget predecessor = null;
171                 TouchTarget target = mFirstTouchTarget;
172                 while (target != null) {
173                     final TouchTarget next = target.next;
174                     if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
175                         handled = true;
176                     } else {
177                         final boolean cancelChild = resetCancelNextUpFlag(target.child)
178                                 || intercepted;
179                         if (dispatchTransformedTouchEvent(ev, cancelChild,
180                                 target.child, target.pointerIdBits)) {
181                             handled = true;
182                         }
183                         if (cancelChild) {
184                             if (predecessor == null) {
185                                 mFirstTouchTarget = next;
186                             } else {
187                                 predecessor.next = next;
188                             }
189                             target.recycle();
190                             target = next;
191                             continue;
192                         }
193                     }
194                     predecessor = target;
195                     target = next;
196                 }
197             }
198 
199             // Update list of touch targets for pointer up or cancel, if needed.
200             if (canceled
201                     || actionMasked == MotionEvent.ACTION_UP
202                     || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
203                 resetTouchState();
204             } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
205                 final int actionIndex = ev.getActionIndex();
206                 final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
207                 removePointersFromTouchTargets(idBitsToRemove);
208             }
209         }
210 
211         if (!handled && mInputEventConsistencyVerifier != null) {
212             mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
213         }
214         return handled;
215     }

我了个叉,和View中这个方法比起来是不是量级瞬间增加不少,不过不用怕,我们着重分析重点部分,一点点来分析,再难也能攻破。

第13行定义一个变量handled,这个变量值在后续会改变,最后作为整个函数返回值返回。

第19-24行如果是手指按下的操作则执行cancelAndClearTouchTargets(ev)与resetTouchState()方法逻辑这两个方法都干了什么呢?看上面的注释以及方法注释就知道差不多了,就是清楚一些之前的标记,状态。不过在cancelAndClearTouchTargets方法里面有个需要注意的点就是在其方法内调用了clearTouchTargets()方法,这个方法源码如下:

 1     /**
 2      * Clears all touch targets.
 3      */
 4     private void clearTouchTargets() {
 5         TouchTarget target = mFirstTouchTarget;
 6         if (target != null) {
 7             do {
 8                 TouchTarget next = target.next;
 9                 target.recycle();
10                 target = next;
11             } while (target != null);
12             mFirstTouchTarget = null;
13         }
14     }

 

第12行将mFirstTouchTarget置为null,这里我们需要特别注意,其实也是将之前记录的状态清空的操作,但是后续会对mFirstTouchTarget进行多次判断,贯穿整个主线,需要特别注意。

好了,回到dispatchTouchEvent方法中,我们继续向下分析:

第28-42行。

第28行定义一个intercepted变量,默认false。

第29,30行进行if判断,如果是ACTION_DOWN事件或者mFirstTouchTarget != null则会进入判断,在我们第一次按下手指点击的时候显然执行的是ACTION_DOWN事件,但是到这里mFirstTouchTarget依然为 null,所以第一次按下手指的时候是可以进入判断的,我们继续向下分析。

第31行 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0这又是什么鬼玩意呢?其实在ViewGroup中有个方法可供外部调用设置mGroupFlags的值(mGroupFlags是ViewGruop中定义的一个变量)。源码如下:

 1     public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
 2 
 3         if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
 4             // We're already in this state, assume our ancestors are too
 5             return;
 6         }
 7 
 8         if (disallowIntercept) {
 9             mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
10         } else {
11             mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
12         }
13 
14         // Pass it up to our parent
15         if (mParent != null) {
16             mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
17         }
18     }

 核心就是8-12行代码,如果我们设置为true,再结合dispatchTouchEvent方法31行代码 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;会得出disallowIntercept最终为true。同样我们设置为false,会得出disallowIntercept最终为false。默认情况下disallowIntercept经过位运算为false。(这种按位操作进行判断的方式很多同学看起来可能不习惯,没办法基本功而已,源码中很多这种判断方式,希望大家都私下搞明白)

我们继续向下探究,32行代码,不用多余解释了吧,默认情况下是成立的,除非我们调用requestDisallowInterceptTouchEvent方法设置为false。

33行代码,调用onInterceptTouchEvent将其返回值赋值给intercepted,onInterceptTouchEvent这个方法大家还记得吧,上面提到过的。系统默认返回false

好了,到这里28-42行代码逻辑我们可以总结一下了:

这部分代码主要做了一件事就是根据不同设置改变intercepted变量的值。

如果我们调用requestDisallowInterceptTouchEvent设置为true,那么就不会执行到33行,而是执行36行代码将intercepted置为false。

默认情况下,是会执行33行代码,也就是说默认情况下,intercepted值是由onInterceptTouchEvent方法返回值决定的。

其实onInterceptTouchEvent返回值主要用来决定ViewGroup是否将触摸事件传递给具体View,起到事件拦截的作用。而如果我们调用requestDisallowInterceptTouchEvent设置为true,则无论onInterceptTouchEvent返回什么值,都会将触摸事件继续向下传递,起到禁止父布局拦截事件的作用。

好了,接下来我们继续向下分析,51-52行代码就是检测分发事件是否取消,然后赋值给canceled变量,默认为false,不取消。

56-57行代码定义newTouchTarget alreadyDispatchedToNewTouchTarget 变量,newTouchTarget后续用于纪录最终接收Touch事件的View。alreadyDispatchedToNewTouchTarget 用于纪录事件是否传递给子View,或者说是否有子View成功处理了Touch事件,有则置为True.

58行代码判断如果事件没被取消或者拦截则if判断成立进入58-160行代码逻辑判断。默认情况下if判断是成立的。

68-70行代码判断是否是各种ACTION_DOWN事件。

80-85行主要做了子View个数的判断以及获取子View的集合preorderedList 。

89-94行,for循环preorderedList 集合获取每个子View。这里需要说明一下:ViewGroup在addView的时候后添加的会显示在上层,我们点击View的时候肯定是想先让浮于上层的View响应触摸事件,从集合preorderedList 中取View的时候默认情况下是倒序获取的。(这里只是简单说一下,不是本文重点)

接下来,107-111行判断当前View是否能相应触摸事件以及触摸点是否在View所在区域内,如果均不成立则跳过此次循环继续下次循环。

122行,这里就是重点了,if判断调用dispatchTransformedTouchEvent方法,这个方法是做什么呢?源码如下:

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

这个方法起初我是看了好长时间,其实核心就是55-66行代码,对第三个参数child是否为空的判断,如果为空,则调用父类的dispatchTouchEvent方法,我们知道ViewGroup继承自View,也就是调用View中的dispatchTouchEvent方法。如果child不为空则调用child自身的dispatchTouchEvent方法,但是要知道child可能是View也可能是ViewGroup。对的,其实这里是有递归的思想的,先分析到这,稍后再回头来看这个方法。

回到122行代码,if判断调用dispatchTransformedTouchEvent方法,按照我们的Demo来分析,这里第三个参数传入的是我们自定义的WLButton ,按照上面的分析child不为空,会调用child自身的dispatchTouchEvent方法,这里也就是View中的dispatchTouchEvent方法,对于View的dispatchTouchEvent方法上篇已经分析过,这里不再多说。默认情况下,WLButton中dispatchTransformedTouchEvent会返回true,所以122行中dispatchTransformedTouchEvent方法也会返回true,表明当前child已经消耗掉此触摸事件,if判断成立。

继续向下看,138-139行代码为newTouchTarget赋值,并将alreadyDispatchedToNewTouchTarget 赋值为true,表明已经找到子View并且子View已经消耗此事件。

138行代码有个需要特别注意的地方,addTouchTarget方法里面为mFirstTouchTarget同样也赋值了,如下第四行代码:

1     private TouchTarget addTouchTarget(View child, int pointerIdBits) {
2         TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
3         target.next = mFirstTouchTarget;
4         mFirstTouchTarget = target;
5         return target;
6     }

140行执行break,跳出整个循环。

好了,58-160行代码到此为止主要逻辑已经讲完,我们回头总结一下主要做了什么。

其实58-160行代码主要就做了一件事,在事件为ACTION_DOWN的时候查找有没有能消耗触摸事件的子View,遍历每一个子View,如果此View能消耗当前事件则跳出整个循环并且为mFirstTouchTarget 赋值。

以上主要是在ACTION_DOWN情况下进行的逻辑判断,163行以后无论什么情况下都会执行。

163行对mFirstTouchTarget 进行是否为null判断,我们知道在ACTION_DOWN情况下会查找是否有子View能消耗当前触摸事件那么mFirstTouchTarget 则不为null,如果没有则为null。

如果没有找到子View能处理当前触摸事件,则进入if判断,165行我们看到又会执行dispatchTransformedTouchEvent方法,注意此时传入的child为null,还记得我们上面分析的dispatchTransformedTouchEvent方法吗,当child为null的时候会调用View的dispatchTouchEvent方法,将当前ViewGroup当作普通View对待,依次调用onTouch以及onTouchEvent方法。

mFirstTouchTarget不为null时,继续传递给子View进行处理,依然是递归调用dispatchTransformedTouchEvent()方法来实现。

到你应该明白为什么事件传递是先传给子View处理,如果子View没有能处理的那么在传递给父类处理了吧,对的源码中关键就是dispatchTransformedTouchEvent方法中第三个参数是否为null。

好了,到此为止ViewGroup中我想说的也就讲解完了。如果你能将上述都理解了,那么开头的那几个小问题应该都不是问题了。

ViewGroup的事件传递机制有些地方还是挺绕的,不过确实很重要,希望大家静下心来好好理解其中核心点。

最后便于理解,附上一张流程图,如果图上每一个关键点你都能回忆起源码中相关核心代码那么你已经掌握差不多了:

 

 

下一篇,我们讨论一下Activity中的事件传递机制,过了ViewGroup这关,其余都是毛毛雨了。

 

posted @ 2017-09-05 11:36  WangLei_ClearHeart  阅读(1021)  评论(0编辑  收藏  举报