网上关于事件分发的博文很多,每一篇都具有一定的特色,但并不是适合每个人看,本篇博文主要包含ViewGroup中事件分发方法的源码分析,附上流程图,伪代码说明,逻辑文字说明,可以主要看文字说明就能理解整个流程,加上自己稍微的思考,就能准确分辨事件分发过程中,每一个环节的改变所带来的走向变化。
ViewGroup中的事件分发的主要方法为 dispatchTouchEvent 方法,dispatchTransformedTouchEvent 方法,主要针对这两个方法作分析就可以明白事件分发的流程。
说明:文中所提到的super.dispatchTouchEvent为View的分发事件的方法,在后面也会稍作说明。mFirstTouchTarget字段为ViewGroup中的一个字段。
down事件:1)如果不拦截则执行child view的dispatchTouchEvent方法(也就是向下传递)并取返回值:
a:如果返回值为true,则 mFirstTouchTarget 字段赋值,
b:如果返回值为false,则执行super.dispatchTouchEvent方法(也就是自己处理)。
2)如果拦截了则执行super.dispatchTouchEvent方法。
move,up事件:1)如果mFirstTouchTarget 为null则直接执行super.dispatchTouchEvent方法。
2)如果mFirstTouchTarget 不为null,则会执行拦截事件的方法:
a:如果不拦截,执行child view的dispatchTouchEvent方法。
b:如果拦截,设置mFirstTouchTarget=null,并把ACTION_CANCEL传给child view的dispatchTouchEvent
/**
* {@inheritDoc}
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// 1.down事件下来时,清除之前的target对象
// Handle an initial down.
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();
}
//2.判断是否拦截该事件,如果是down事件或者是mFirstTouchTarget不为null则会根据
// disallowIntercept判断是否执行拦截事件的方法,如果disallowIntercept为false
// 则表示允许拦截,执行拦截事件方法,如果为true则默认不可拦截。
// 如果不是down事件或者mFirstTouchTarget为null则直接拦截该方法,intercepted为true
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// 3.判断是否取消事件
// 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;
// 4. 如果没有取消并且没有拦截 进入分支,判断是down事件或者是多指down事件 则通过
// dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)方法把事件传
// 递子view的dispatchTouchEvent方法,并通过标志位
// alreadyDispatchedToNewTouchTarget记录住子viewdispaTouchEvent方法的返回值,如
// 果子view处理了事件mFirstTouchTarget赋值。
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
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 (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
// 5.如果mFirstTouchTarget为null,通过dispatchTransformedTouchEvent方法把事件传递给
// handled=super.dispatchTouchEvent(event)也就是View方法的dispatchTouchEvent方
// 法,并记录返回值。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
// 6. FirstTouchTarget不为null,如果alreadyDispatchedToNewTouchTarget为true表示已经
// 把事件传给了子view,否则则通过dispatchTransformedTouchEvent把事件传递给子view,
// 此次传递给子view如果是拦截了事件会把ACTION_CANCEL传给子view并把mFirstTouchTarget
// 至为null
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
上述代码主要关注的是中文注释,通过中文注释,主要把dispatchTouchEvent方法分成了6块,分析这6块的逻辑就能准确的了解事件分发的逻辑:
1)down事件下来时,清除之前的target对象
// Handle an initial down.
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();
}
事件的分发都是从down事件开始的,每次down事件下来就表明从新开始了,这时候就要把之前的一些标志位和相关字段初始化。
2)判断是否拦截该事件,如果是down事件或者是mFirstTouchTarget不为null则会根据disallowIntercept判断是否执行拦截事件的方法,如果disallowIntercept为false则表示允许拦截,执行拦截事件方法,如果为true则默认不可拦截 如果不是down事件或者mFirstTouchTarget为null则直接拦截该方法,intercepted为true
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
在down事件初始话完了之后,就要开始真正传递事件了,这个时候要准备执行拦截事件的方法了,不过要执行拦截事件的方法有几个条件,一,是该事件是否是down事件或者mFIrstTouchTarget不为null,mFIrstTouchTarget不为null的意义是表示有子view处理了该事件,也就是说该事件要往子view传递,down事件也是要往子view传递的事件,也就是说如果事件不需要往子view传递,那么就不需要执行拦截事件的方法。二,是是否允许拦截,disallowIntercept字段为true表示不许拦截,该字段的值可以通过子view调用getParent.requestDisallowIntercepTouchEvent改变。
3)判断是否取消事件
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
4)如果没有取消并且没有拦截 进入分支,判断是down事件或者是多指down事件 则通过 dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)方法把事件传递 子view的dispatchTouchEvent方法,并通过标志位alreadyDispatchedToNewTouchTarget 记录住子viewdispaTouchEvent方法的返回值,如果子view处理了事件 mFirstTouchTarget 赋值。
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
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 (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
整个if里面代码很复杂,但是总结起来却很简单,就是如果事件没有取消,没有被拦截,并且是down事件的时候,将该事件通过dispatchTransformedTouchEvent传递给子view的dispatchTouchEvent方法,优先给子view处理该事件,如果子view处理了,返回值为true,则给mFirstTouchTarget字段赋值。
5)如果mFirstTouchTarget为null,通过dispatchTransformedTouchEvent方法把事件传递给handled =super.dispatchTouchEvent(event)也就是View方法的dispatchTouchEvent方法,并记录 返回值。
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
这一段代码也是比较简单,就是在mFirstTouchTarget为null,此时表示没有子view要处理了该事件,就通过dispatchTransformedTouchEvent方法把事件传递给super的dispatchTouchEvent方法,也就是自己处理该事件。此后,子view已经接受不到了事件。
6)mFirstTouchTarget不为null,如果alreadyDispatchedToNewTouchTarget为true表示已经把事件传给了子view,否则则通过dispatchTransformedTouchEvent把事件传递给子view,此次传递给子view如果是拦截了事件会把ACTION_CANCEL传给子view并把mFirstTouchTarget至为null。
else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
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;
}
}
这一段代码的主要逻辑就是,如果子view处理了事件,根据我们的拦截方法返回值判断是否要再次把事件传给子view,如果拦截了事件,则把一个ACTION_CANCEL事件传递给子view,告诉子view事件取消了,并把mFirstTouchTarget设置为null,往后不在传递事件给子view了,这里面有一个标志位alreadyDispatchedToNewTouchTarget,就是down事件在之前有传递给了子view,这个字段记录了就表示这次事件不在传了。
以上的这些,都是对dispatchTouchEvent方法中源码的解析,重要是关注其中讲到的6个流程,这些事事件传递过程中需要重点关注的地方。
void dispatchTouchEvent(event){
//一
if(down){
重置之前的targrt
}
//二
if(down || mFirstTarget不为null ){
if(可以拦截){
onIntercept方法
}else{
不拦截
}
}else{
默认拦截
}
//三
判断是否取消
//四
if(没拦截并且没取消){
if(down事件){
遍历子view找到对应的子view并执行子view的dispatch方法
如果子view的dispatch方法返回true,复制mFirstTouchTarget
}
}
//五
if(mFirstTarget==null){
super的dispatch方法
}else{
//六
if(down,也就是标志位子view已经处理了事件){
handled=true
}else{
//到了这里也就是表示不是down事件并且mFirstTarget不为null
把事件传递给子view,如果方法有被拦截则传递的是ACTION_CANCEL事件,并把mFirstTouchTarget置为null
}
}
}
这一段伪代码,也是对几个重要步骤的归纳,主要是为了方便记忆。
说明:图中黑色线条以及文字表示down事件的流程,其它的表示move,up事件的流程。
流程说明:
down事件:1)如果不拦截则执行child view的dispatchTouchEvent方法(也就是向下传递)并取返回值:
a:如果返回值为true,则 mFirstTouchTarget 字段赋值,
b:如果返回值为false,则执行super.dispatchTouchEvent方法(也就是自己处理)。
2)如果拦截了则执行super.dispatchTouchEvent方法。
move,up事件:1)如果mFirstTouchTarget 为null则直接执行super.dispatchTouchEvent方法。
2)如果mFirstTouchTarget 不为null,则会执行拦截事件的方法:
a:如果不拦截,执行child view的dispatchTouchEvent方法。
b:如果拦截,设置mFirstTouchTarget=null,并把ACTION_CANCEL传给child view的dispatchTouchEvent
dispatchTransformedTouchEvent的源码:
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
这一段源码比较简单,稍微看看就能理解,通过参数child是否为null判断是传给ziview还是super。
1)如果有设置onTouchListener的监听,可以触摸,则执行重写的onTouch方法,并记录该
方法的返回值
2)如果没有设置onTouchListener的监听,或者重写的onTouch方法返回false,则会接着
执行onTouchEvent方法,并记录其返回值。
3)performClick方法在onTouchEvent方法中被执行。