一篇文章读懂android事件消费、事件分发、事件拦截
Android 源码分析事件分发机制、事件消费、事件拦截
解决SwipeRefreshLayout和ViewPager滑动冲突的三种方案
1.前言
事件分发这个东西嘛,大家一直都在讲,但总有人觉得吃不透。为什么呢?因为事件分发是多维的,有好多条思维分岔路口,而文章基本上只能用一维的方式从左到右,从上到下进行表达,所以基本不可能让普通智力的人从入门到精通。我们所要做的,就是踏踏实实打开源码,自己多琢磨,多整理。读源码切记要从宏观的角度去看问题,不然往往会深陷细节出不来了,我们自己想想也知道,别人的框架可能10几个人,耗时几个月或者一年完成的,你能一两天、几个星期读个源码就都掌握么。要摸细节的话,你要带着问题有目标的去读,常读常新,每次有收获就行
下面内容请配合源码食用!不然基本上索然无味
读过上一篇文章,相信你对事件的消费、分发和拦截在宏观上,都有了一定的了解,这篇文章我们从源码分析,加深了解。
ViewGroup
- 我们先走正常流程,假设一开始没被拦截,为了方便下面的描述直接贴出viewgroup#dispatchTouchEvent的代码
@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;
// 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();
}
// 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);
}
// 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;
if (!canceled && !intercepted) {
// If the event is targeting accessibility 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<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, 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.
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;
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;
}
我们知道一个事件组都是从down事件开始的,所以我们从触摸事件的起点事件开始分析
Down
一开始进入ACTION_DOWN判断,首先会重置一些状态变量的值,也就是每次down事件开始,都会重置上一次事件的变量,现在我们假设事件DOWN没被拦截,我们走到这句 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;因为一开始mGroupFlags等于0,0&任何值都是0;0!=0,所有disallowIntercept是false, false就走入intercepted = onInterceptTouchEvent(ev);这句,因为一开始没被拦截,所有intercepted也就是onInterceptTouchEvent(ev)的默认返回值false,一开始肯定也是没有取消的,所以canceled也为false,newTouchTaget一开始初始化为null,alreadyDispatchedToNewTouchTarget = false,进入if (!canceled && !intercepted) {,childrenCount就是子view的数量,因为dispatchTouchEvent方法是从根向上开始走的,所以只要页面有view就肯定不为0,直接进入buildTouchDispatchChildList()对子view排序,排序完成赋值给ArrayList<View> preorderedList数组,我们点进buildTouchDispatchChildList看看是怎么排序的
for (int i = 0; i < childrenCount; i++) {
// add next child (in child order) to end of list
final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
final View nextChild = mChildren[childIndex];
final float currentZ = nextChild.getZ();
// insert ahead of any Views with greater Z
int insertIndex = i;
while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) {
insertIndex--;
}
mPreSortedChildren.add(insertIndex, nextChild);
}
如果插入的view的z坐标的数值大于当前view的z值,就插mPreSortedChildren,然后insertIndex--一直循环插入完为止。
简单的来说,这个排序完,就是z轴的值越大越排在数组的后面(我们知道,从z方向看,父view一直是在子view的下面的,子view一直是往x轴正方向叠加的)
我们接着看,for (int i = childrenCount - 1; i >= 0; i--) {,又从数组最末端开始for循环取出对应的view,所以我们最先拿出最顶部的子view,也就是我们点击事件的时候最先接触的那个子view。顶部向底部一层层拿到对应的view后,然后通过canViewReceivePointerEvents方法判断这个view是不是VISIBLE显示状态,如果是VISIBLE,再通过isTransformedTouchPointInView判断这个view的x、y值和当前点击的位置是否是对应的,如果这个view就是你当前点击的,就返回true
如果不通过判断直接continue,进入循环进入下一个view,通过验证判断则进入if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {,在
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;
}
// 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;
}
因为child是有值的,所以进入handled = child.dispatchTouchEvent(event);,
调用子view的dispatchTouchEvent方法,如果child是ViewGroup,就相当于重新执行上面的一大波步骤;如果child是View,则类似于父View拦截事件的过程,会执行View本身的Touch或Click方法,我们这里假设child是view不是ViewGroup,我们知道view类的dispatchTouchEvent方法里,如果onTouchEvent(event)返回true就代表view消费了这件事件,所以 handled = child.dispatchTouchEvent(transformedEvent);
handled就是true,所以dispatchTransformedTouchEvent就是true,返回到之前代码,我们接着看如果这个view消费了这个down事件,这个if里接下来会做什么处理,
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;
}
在循环最后我们看到有一个break,也就是如果有一个子view处理了事件,整个for循环就break跳出了,所以这个点击事件直接交给子view来处理了,不再循环,它的父view就接受不到这个事件了,当然前面如果一直没有进入if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {这个循环就会一直沿着
z轴的负方向去找这个子view的父view、父亲的父view、、、、直到找到对应的父view来处理。
我们再看看在跳出dispatchTransformedTouchEvent的这个if之前,有两个赋值操作newTouchTarget = addTouchTarget() ===> newTouchTarget =mFirstTouchTarget;alreadyDispatchedToNewTouchTarget = true;
这两个赋值完才breadk的,break跳出循环后,我们接着看进入mFirstTouchTarget != null这个判断(因为前面赋值了)
while (target != null) {因为target第一次等于mFirstTouchTarget不为空,第二次等于target.next.mFirstTouchTarget是为空的,所以这个while循环只走一次,
我们再往下看,因为之前我们对alreadyDispatchedToNewTouchTarget和newTouchTarget赋值了,所以进入这个if
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
将handled赋值为true,最后再return handled,也就是整个dispatchTouchEvent方法return true,到此,整个Down事件处理结束。这个是正常的down事件,是没有被拦截的,
假如被拦截呢?,我们再回到ViewGroup#dispatchTouchEvent看看,
假如第一次进来被拦截的话,也就是如果我们如果在ViewPager里重写onInterceptTouchEvent并且返回true的时候,intercepted = onInterceptTouchEvent(ev);返回true;也就是Viewpager里拦截了事件,通过前面,我们知道事件分发是从父容器分发到子容器的,之前的if就不进去了,直接被拦截在Viewpager层了,后面的都不会分发到子view了,所以我们越过之前那个if (!canceled && !intercepted) {,接下去看if (mFirstTouchTarget == null) {
因为第一次进入,也没有进入过f (!canceled && !intercepted) {,所以mFirstTouchTarget没被赋值是为null的,所以进入if (mFirstTouchTarget == null) {这个if判断,所以会直接也会进入dispatchTransformedTouchEvent,只不过传进去的这个child默认是null了,我们再点进去dispatchTransformedTouchEvent看看
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分支,直接进入 handled = super.dispatchTouchEvent(transformedEvent);所以也调用到View类的dispatchTouchEvent方法里去分发事件,请注意!虽然最后代码跑到了View中,但这个View是ViewGroup的父类!也就是说最终执行的Touch或Click方法依然是外层ViewGroup中重写的Touch或Click方法!请区分ViewGroup、View、父View与子View的区别~。
事件DOWN在之前已经是被最顶部的view拿到了,再看看MOVE事件是怎么处理的。
Move
Move也是进入ViewGroup的dispatchTouchEvent方法,一开始还是会进入
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事件处理,所以mFirstTouchTarget不为null,所以MOVE事件也能够被拦截的原因就在于这个if判断。接着看,现在是MOVE事件也没有被取消,我们还是假定没被拦截的情况,所以直接进入 if (!canceled && !intercepted) {判断,因为我们现在是Move事件,所以也没有preorderedList循环子view分发事件的操作。我们接着往下,直接进入mFirstTouchTarget != null分支,这里注意了,虽然mFirstTouchTarget没有被重置,但alreadyDispatchedToNewTouchTarget在进入之前进入循环之前会被置为false;所以进入里面的else的分支,进入dispatchTransformedTouchEvent方法,因为intercepted == false,所以dispatchTransformedTouchEvent传入的cancelChild也为false,所以我们次再进入dispatchTransformedTouchEvent方法看看,因为经过Down事件child也是不为null的,所以进入handled = child.dispatchTouchEvent(transformedEvent);MOVE事件就是在这里进行分发与回调的!所以dispatchTransformedTouchEvent就是true,返回到之前代码,我们接着看如果这个view消费了这个down事件,这个if里,执行 handled = true;
最后再return handled,也就是整个dispatchTouchEvent方法return true,到此,整个Move事件也处理结束。
虽然MOVE和DOWN都是交由View本身的onTouchEvent()方法执行,但是但因为动作类型MotionEvent不同,也是不同操作的,这里就讲一个点,如果是ACTION_UP类型,则执行performClick()方法。在performClick方法里,会监听onClick()方法(如果你通过setOnClickListener为当前View设置了Click监听)。
getParent().requestDisallowInterceptTouchEvent(true)
大家都用过这个方法,我们知道在子view里调用父view的requestDisallowInterceptTouchEvent(true)方法,方法里传入true,这样就能通知到父view不要在事件流里拦截我了,我们看到源码是具体怎么实现的。
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
// We're already in this state, assume our ancestors are too
return;
}
if (disallowIntercept) {
mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
} else {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
// Pass it up to our parent
if (mParent != null) {
mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
我们知道在调用requestDisallowInterceptTouchEvent方法的时候,入参传入true的时候,会执行这句代码mGroupFlags |= FLAG_DISALLOW_INTERCEPT;把mGroupFlags赋值为mGroupFlags |FLAG_DISALLOW_INTERCEPT,并且递归调用,只要父View不为null, 就把父View的FLAG同样设置。
之前在viewgroup的dispatchTouchEvent方法里有这么一段代码
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;
}
我们看到这句final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;现在mGroupFlags为mGroupFlags |FLAG_DISALLOW_INTERCEPT,所以现在mGroupFlags和FLAG_DISALLOW_INTERCEPT一做 & 操作就是等于FLAG_DISALLOW_INTERCEPT,所以disallowIntercept是为true,就不会走
intercepted = onInterceptTouchEvent(ev);也就是就算父view内部重写了onInterceptTouchEvent(ev);我这边通过改变mGroupFlags标志位,直接把intercepted设置为false,直接不设置拦截。
通过一个事件组,分析完ViewGroup里的dispatchTouchEvent方法,我们得出的结论其实就是上一篇文章里讲的重点:
- 1、事件都是以事件组的形式存在的,开始于DOWN事件结束于UP事件或者ACTION_CANCEL事件。
- 2、在一个事件组中,你最终每执行一个事件(down、move)就会走一次onTouchEvent。
- 3、事件分发都是从顶部的子view开始,向下传递的,如果第一个view的onTouchEvent对这个DOWN事件没有响应,就一直向下传递,直到遇到第一个对这个DOWN事件作出响应的View,这个向下的DOWN事件就会结束,并接下来的move事件也交于这个view处理。
- 4、在事件从顶部的子view开始分发之前,Android会从这个Activity里面最底部的那个根view,向上去一级一级的询问:你要不要拦截这组事件?拦截的意思就是事件不交给子view了,我自己来处理。具体在实现上,就是通过调用viewGroup的onInterceptTouchEvent方法返回true来实现的。
- 5、还有一个就是requestDisallowInterceptTouchEvent,子view里调用父view的requestDisallowInterceptTouchEvent(true)方法,方法里传入true,这样就能通知到父view不要在事件流里拦截我了,源码实际是通过改变标志位mGroupFlags来实现的。
- 6、如果一个view设置了setOnClickListener监听和setOnTouchListener监听,只有在setOnTouchListener的onTouch返回false,才会走setOnClickListener里的onClick方法;如果在setOnTouchListener的onTouch返回true,此时只走onTouch,不走setOnClickListener里的onClick方法。
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//onTouchEvent内部间接调用了setOnClickListener的onClick方法
if (!result && onTouchEvent(event)) {
result = true;
}
最后有空的可以看下ScrollView嵌套ScrollView的滑动冲突这篇文章,带着源码requestDisallowInterceptTouchEvent的思路,看看滑动冲突的解决,趁热带铁,效果更佳。