写在前面
最近需要回放一些点击事件,但是时不时会回放失败(很尴尬的Bug),所以去看了一下点击事件的传递流程,这一篇文章主要讲一下点击事件是如何在ViewGroup中传递的。这是一个对理解点击事件传递很有帮助的文章,关于MotionEvent的。
从网上查找资料,可以得知,点击事件TouchEvent会经过一系列的传递,传到ViewGroup中的dispatchTouchEvent()中,代码如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
//判断MotionEvent是否指定了View对象,如果有,则在后面直接把它交给指定对象处理
........
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
//清除之前的一些状态
.......
// Check for interception. 检查是否拦截该事件
final boolean intercepted;
.......
// 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 (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; //事件有指定的View对象,跳过其他的子View
}// 优先处理指定View对象,然后再传递事件给其他子View
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
.......
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;
}
}
......
return handled;
}
本着不看不看,无关不看,不懂不看的原则,将代码精简了一下。下面我们来看一下重点的代码:
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;
}
传递的第一个TouchEvent的Action是ACTION_DOWN,这也意味着newTouchTarget是null,所以在不停止不拦截的情况下会进入上面的代码段,在上面的代码中会执行dispatchTransformedTouchEvent方法,在这个方法中将点击事件传递给子View,如果子View处理该事件,则将子View的索引记录在mLastTouchDownIndex中,并调用addTouchTarget生成一个新的TouchTarget,以此保留对此view的引用,方便处理以后的事件,这个TouchTarget对象以链表的形式保存,并采用头插入的方式。通常情况下这一步完成之后,newTouchTarget和mFirstTouchTarget就都不为null了
PS
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;
}
这一段代码表示,ACTION_DOWN事件没有被处理,但是之前却又处理过ACTION_DOWN事件,所以把这个事件给最近最早处理的那个View处理。猜测情况,一根手指点击了屏幕后,又有另一个手指点击,但是此时没有view愿意处理此事件。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
mFirstTouchTarget为null,表明没有子View愿意处理这一系列的TouchEvent,所以在调用dispatchTransformedTouchEvent时,传递的child参数为null,表示交给自身来处理。
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;
}
在这个循环中,会遍历之前的TouchTarget链表(保存的是一些兄弟View)传递TouchEvent,同时在传递过程中会判断是否对View停止传递。
PS
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
}
这一段代码表示,要跳过之前已经处理的ACTION_DOWN事件。
接下来我们看一下dispatchTransformedTouchEvent方法:
dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits)
它有四个参数,第一个为传递的点击事件,第二个表示是否停止传递,一般都为false,第三个表示要传递给那哪个子View,第四个是一个整型,它的每一位都代表一个点,大概是触摸屏幕的一根手指。一般的点击事件,其值为1
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
......
// 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);
}
这段代码意思大概是,判断此view之前处理事件时的点的数量是否和现在点击事件中点的数量相同(一般情况下都相同),不相同则要对事件进行处理,然后传递处理后的事件。
其中有一个方法child.hasIdentityMatrix(),从它的注释来看表示它是否有一个单位矩阵(一脸懵逼.png),如果有则直接使用当前的点击事件,如果没有,则要把当前的点击事件复制一份进行传递(不管怎样大体上还是往下传递)。代码如下:
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);
}
当child为null时,交给view类的dispatchTouchEvent,然后传递到自身的onTouchEvent去处理,不为null,对TouchEvent中的坐标进行变化,然后向下传递。最后会将handled返回,表示该事件是否被处理。
结束......