网上看到过很多人写的事件分发机制解析,感觉表述都不是很清楚,也可能没有看到写得好的文章,所以自己重新看了一遍源码,来彻底搞清楚Android事件分发机制.
触摸事件有哪些以及怎么从Activity传递到DecorView大家可以上网查下,几个重要方法的基本调用顺序,这些很容易搜到,我们重点关注事件从ViewGroup到View的事件具体的执行过程.
1 Android事件分发涉及到的方法主要有
dispatchTouchEvent()事件分发
onInterceptTouchEvent()拦截事件
onTouchEvent()处理事件
requestDisallowInterceptTouchEvent()请求不要拦截事件
2 测试类介绍
BigGroup类型ViewGroup
SmallGroup类型ViewGroup
TestView类型View*(clickable默认false)
3 默认情况下的事件分发流程(View.onTouchEvent()返回super.onTouchEvent())
log如下所示:
BigGroup: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
BigGroup: onInterceptTouchEvent() called with: ev = [ACTION_DOWN]
SmallGroup: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
SmallGroup: onInterceptTouchEvent() called with: ev = [ACTION_DOWN]
TestView: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
TestView: onTouchEvent() called with: event = [ACTION_DOWN]
SmallGroup: onTouchEvent() called with: event = [ACTION_DOWN]
BigGroup: onTouchEvent() called with: event = [ACTION_DOWN]
我们看到不管怎么点击滑动,都只会触发DOWN事件的流程,我们来看下这是为什么,首先我们来看下ViewGroup的dispatchTouchEvent()
///////////ViewGroup
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...省略部分代码
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
//如果是DOWN事件,清除标记,恢复一些标记状态
if (actionMasked == MotionEvent.ACTION_DOWN) {
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
//判断是否拦截
final boolean intercepted;
//触发DOWN事件或者mFirstTouchTarget不是Null,才会走if里面的逻辑
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.
//不是DOWN事件 mFirstTouchTarget为空 拦截后续事件
intercepted = true;
}
...省略部分代码
// 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中逻辑
if (!canceled && !intercepted) {
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 (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//判断child是否可以响应事件 是否点击在了View的范围之内
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//获取上次响应事件的View,DOWN事件时候newTouchTarget为Null
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();
//在这个方法中把child赋值给了mFirstTouchTarget
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
...
}
}
// 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;
}
}
...
}
...
return handled;
}
//最重要的几行代码的逻辑
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
...省略部分代码
// Perform any necessary transformations and dispatch.
//child为空调用父View的dispatchTouchEvent
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());
}
//child不为空调用child的dispatchTouchEvent方法
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
//默认返回false
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}
//////////View
public boolean dispatchTouchEvent(MotionEvent event) {
...
boolean result = false;
...
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
//我们看到有mOnTouchListener,并且onTouch返回true,就没有onTouchEvent啥事了
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
...
return result;
}
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
...
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
...
break;
case MotionEvent.ACTION_DOWN:
...
break;
case MotionEvent.ACTION_CANCEL:
...
break;
}
return true;
}
return false;
}
我们梳理下DOWN事件的执行流程:
1 触发BigGroup的dispatchTouchEvent()方法
2 给intercepted赋值,disallowIntercept默认为false,这是就会触发onInterceptTouchEvent()方法,onInterceptTouchEvent默认返回false.intercepted赋值为false
3 接下来走到if (!canceled && !intercepted)的逻辑里面去了,注意注意intercepted为true的话这个方法直接就跳过去了.在这段逻辑里遍历所有的子View,接下来进入淘汰机制,child不能获得焦点,下一个,然后看看View不可见,下一个,没有点到child范围之内,下一个.剩下来的娃会执行dispatchTransformedTouchEvent方法
4 接下来dispatchTransformedTouchEvent中调用了child的dispatchTouchEvent方法
5 执行dispatchTouchEvent的child就是我们的SmallGroup,执行逻辑同2-4
6 这次执行dispatchTouchEvent的child就是我们的TestView了
7 TestView dispatchTouchEvent中首先判断了有没有onTouchListener,判断onTouch方法的返回值.我们肯定没写的了,接下来会执行onTouchEvent
8 在TestView onTouchEvent中我们看到如果这个View可点击就返回true,不可点击就返回false.TestView不可点击,所以返回了false
9 触发了连锁反应,TestView dispatchTouchEvent返回false
10SmallGroup dispatchTransformedTouchEvent返回了false, mFirstTouchTarget为null
11SmallGroup再次执行dispatchTransformedTouchEvent child参数为null,执行super.dispatchTouchEvent(),ViewGroup的super最后就是View,所以会执行逻辑7-9,不同的事主角事SmallGroup
12BigGroup dispatchTransformedTouchEvent返回了false, mFirstTouchTarget为null,重复步骤11,主角BigGroup,DOWN事件结束
mFirstTouchTarget为null会有什么影响呢?后续事件中intercepted为true,执行dispatchTransformedTouchEvent child参数为null,执行super.dispatchTouchEvent(),事件直接传递不下来了,后续事件都接收不到了
4 onInterceptTouchEvent()直接返回true
LOG如下所示:(在SmallGroup onInterceptTouchEvent中return true)
BigGroup: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
BigGroup: onInterceptTouchEvent() called with: ev = [ACTION_DOWN]
SmallGroup: dispatchTouchEvent() called with: ev = [ACTION_DOWN]
SmallGroup: onInterceptTouchEvent() called with: ev = [ACTION_DOWN]
SmallGroup: onTouchEvent() called with: event = [ACTION_DOWN]
BigGroup: onTouchEvent() called with: event = [ACTION_DOWN]
按照我们之前的步骤分析,SmallGroup的onInterceptTouchEvent中返回true,那么事件就不会向下执行,由于mFirstTouchTarget为null,所以后续事件我们都接收不到了.
如果在SmallGroup的onTouchEvent中返回true,就可以收到后续事件.但是SmallGrou的onInterceptTouchEvent只会执行一次.我们来思考下为什么?
我们在SmallGroup的onInterceptTouchEvent中返回true,那么SmallGroup的mFristTouchTarget就是null;因为我们在SmallGroup的onTouchEvent中返回true,所以SmallGroup的dispatchTouchEvent也返回true.那么GigGroup的mFristTouchTarget不是null,所以事件才能延续,由于不满足事件为DOWN,也不满足mFristTouchTarget!=null,所以不会走到拦截方法里面.
5 为什么父View不要拦截DOWN事件?
SamllGroup 的onInterceptTouchEvent()直接返回true,我们在TestView中调用getParent().requestDisallowInterceptTouchEvent(true),会有效果吗?
不会,为什么呢?onInterceptTouchEvent直接返回true拦截的话,getParent().requestDisallowInterceptTouchEvent(true)根本就执行不到,所以一般情况下不要拦截DOWN事件.
getParent().requestDisallowInterceptTouchEvent(true)成功以后会有什么现象呢?
disallowIntercept变量为true,所有的onInterceptTouchEvent方法都不会在执行.
6总结
dispatchTouchEvent()
onInterceptTouchEvent()
onTouchEvent()
requestDisallowInterceptTouchEvent()
搞明白这几个事件的顺序及调用时机,以及调用有哪些限制.我们就明白了Android的事件分发机制.mFirstTouchTarget是一个很重要的变量,大多数情况下,它影响onInterceptTouchEvent的调用情况,进而影响事件是否往下传递.onTouchEvent()的返回值很大程度上决定了dispatchTouchEvent方法的返回值.dispatchTouchEvent返回false,后面的事件就基本没它啥事了.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。