标签:
以前看了很多人介绍的Android事件派发流程,但最近使用那些来写代码的时候出现了不少错误。所以回顾一下整个流程,简单介绍从手触摸屏幕开始到事件在View树派发。从源码上分析ViewGroup.dispatchTouchEvent。
Android的事件产生是从我们触摸屏幕开始,在经过Input子系统,最后达到我们的应用程序(或者经过WindowManagerService到达应用程序)。
而其中Input子系统在Java层对应着InputManagerService,其主要在native层,由InputReader读取EventHub的元数据,将这些数据加工成InputEvent,最后发到InputDispatcher,而InputDispatcher则负责将时间发到应用程序,Input子系统流程可以参见这篇文章Android Framework——之Input子系统。
对于应用层的时间流程,主要是下面的流程图所示:
其中最后一步就是我们经常说的View事件派发流程。另外上面DecorView是经过了两次,第一次是调用DecorView的dispatchTouchEvent,它的源码是:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
final Callback cb = getCallback();
return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
: super.dispatchTouchEvent(ev);
}
Callback就是Window.Callback,Activity实现了这个接口。在Activity的attach函数中,会调用window的setCallback,将Activity设置给Window。所以这里getCallback返回的就是Activity,最终会调用Activity的dispatchTouchEvent。下面看一下Activity的dispatchTouchEvent函数:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
在ACTION_DOWN的时候会调用onUserInteraction方法,然后调用Window(实际上是PhoneWindow)的superDispatchTouchEvent,如果Window的superDispatchTouchEvent消耗了事件,则直接返回,不会调用Activity的onTouchEvent方法。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
而DecorView的superDispatchTouchEvent为:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
最终还是调用DecorView的父类的dispatchTouchEvent,DecorView的父类是FrameLayout,它没实现该方法,最终会调用ViewGroup的dispatchTouchEvent方法。从这里开始就进入了view树的时间派发流程了。
这里从源码上分析事件派发的一些特性。事件派发最开始会进入到ViewGroup的dispatchTouchEvent(DecorVIew父类),下面是ViewGroup的dispatchTouchEvent伪代码的分析,直接在对应的代码部分加了注释:
“`
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//一开始做一些调试验证,另外如果事件的目标是focused view,并且当前view就是一个focused view,
//有可能view的子View就会处理这次事件,所以将targetAccessibilityFocus设置为false。
…
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) { //检查event是否是安全的
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.
//清除之前的事件状态。比如说在app切换,ANR或其他状态改变时,系统框架将会去掉up或cancel事件。在这里会将mFirstTouchTarget清空,mFirstTouchTarget是保存了会接受事件的View处理对象。
cancelAndClearTouchTargets(ev);
resetTouchState(); //这里会将mGroupFlags的FLAG_DISALLOW_INTERCEPT标识清除,
//1. 每次事件流开始的时候都会先清除FLAG_DISALLOW_INTERCEPT,所以子view的requestDisallowInterceptTouchEvent只有当次事件流有效。
}
// 判断是否需要拦截事件,去判断是否拦截事件的条件是此次事件是DOWN事件,或者有子类会处理这次事件(mFirstTouchTarget不为null),并且FLAG_DISALLOW_INTERCEPT没被设置。
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//2. 只有有TouchTarget并且没有被disallow,或者是ACTION_DOWN时才会调用onInterceptTouchEvent。
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 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<View> 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;
}
//判断当前的child是否可以接收事件,并且事件是否在当前的view范围
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);
//3.dispatchTransformedTouchEvent会将Event转化为child坐标空间(getX的变化),然后去除无关的points id,如果有必要更改事件,最后调用child.dispatchTouchEvent。 dispatchTransformedTouchEvent把事件派发给child,如果child成功处理了,则会将child添加到mFirstTouchTarget
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();
//addTouchTarget会创建新的TouchTarget,并将其加入到mFirstTouchTarget
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;
}
}
}
//4. 派发事件
// Dispatch to touch targets.
if (mFirstTouchTarget == null) { //mFirstTouchTarget为空表示没有子View会处理这次事件,则交给当前的ViewGroup处理。
// 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) {//遍历mFirstTouchTarget链表,一个一个地处理TouchTarget。
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {//新添加的不会立刻处理,ACTION_DOWN已经在前面派发了
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
//dispatchTransformedTouchEvent会将Event转化为child坐标空间(getX的变化),然后去除无关的points id,如果有必要更改事件,最后调用child.dispatchTouchEvent
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);
}
}
...
//用于测试的代码
return handled;
}
```
事件派发流程主要集中在这几个方法的调用:
- dispatchTouchEvent 这是事件派发每个View的时候,第一个被调用的方法,如果是ViewGroup,dispatchTouchEvent会先去调用onInterceptTouchEvent是否应该拦截事件,不拦截的话会先从子View中判断是否有处理该次事件的(在ACTION_DOWN中采用mFirstTouchTarget链接保存会处理事件的TouchTarget),如果没有的话则调用当前View的onTouchEvent。
- onInterceptTouchEvent 判断是否应该拦截事件,ViewGroup默认实现是返回false,子View可以调用getParent.requestDisallowInterceptTouchEvent()来阻止父View拦截。否则只要有子View可能消费事件,该方法都会被调用。
- onTouchEvent这个方法是在没有子View将会消耗事件时才会被调用,onClickListener,onTouchListener,onLongClickListener都是在这个方法中处理的。如果返回true表示消费这次事件。
对于事件派发流程,我觉得有几个地方需要注意的:
1. 应该把ViewGroup以及它所包含的子View都看作是这个ViewGroup的一部分,对于一个ViewGroup是否会处理一次事件,应该是包含了它的子View是否也处理。
2. 如果整个ViewGroup以及它的子类没有一个View处理ACTION_DOWN事件,那么下一次就不会调用这个ViewGroup的dispatchTouchEvent。***但是如果ACTION_DOWN返回了true,那么下一次事件还是会继续派发到ViewGroup,即使中间某个ACTION_MOVE返回了false***。
3. onInterceptTouchEvent是在子View可能会处理该次事件,并且没有被设置FLAG_DISALLOW_INTERCEPT才会被调用。正常情况下,它在ACTION_DOWN的时候一定会被调用的,因为在ACTION_DOWN的时候会先调用resetTouchState()。
这个是最近略微改了一下很久之前写的一个模仿QQ邮箱滑动退出写的一个东西:https://github.com/xxxzhi/SlideListener,改的过程发现之前看的东西理解地不够好…
源码是解释很多现象的最根本的原因,阅读源码能够更好地理解事件派发流程,理解地更加深刻。
标签:
原文地址:http://blog.csdn.net/xxxzhi/article/details/51387117