ViewGroup的dispatchTouchEvent理解
以下图例子说明,OFramelayout在最外层
图1.1 view的层级关系
结论1:
dispatchTouchEvent()返回false,后续的ACTION_MOVE、ACTION_UP等收不到。注:dispatchTouchEvent()中判断手势是
ACTION_DOWN时,返回false,则后续的触摸事件收不到,如果返回true,在后续的ACTION_MOVE条件下,不论返回什么都能收到后续触摸响应。类推,在onTouchEvent中是一样的结论。结论2:
如果有对应的OnTouchListener,可以在onTouch中返回true拦截事件,使onTouchEvent()不执行。结论3:
在一次触摸事件中,如果onInterceptTouchEvent()中返回true,则触摸事件由该视图消费,不会再派发。如果onInterceptTouchEvent()先返回false,然后在某个条件返回true,则在起初返回false时,onInterceptTouchEvent()会被一直调用(前提条件是子视图消费了事件并返回了true),返回true后,onInterceptTouchEvent将不会再被调用,不管以后返回啥,onInterceptTouchEvent都不会再被调用。注:前提条件是该视图的dispatchTouchEvent要返回true,也就是说要能持续响应触摸事件。
看到这,大家都会觉得云里雾里,通过研读源码具体分析每个结论,以下基于android 5.0的源码。
结论一研读:
MFramelayout在dispatchTouchEvent()中的ACTION_DOWN条件下返回false,则触控事件首先进入OFramelayout的dispatchTouchEvent()即ViewGroup的dispatchTouchEvent()。进入1956行的判断,disallowIntercept是由requestDisallowInterceptTouchEvent()方法决定的。disallowIntercept为false时表示可拦截事件,然后会调用onInterceptTouchEvent()方法。disallowIntercept默认时为false。然后进入1985行的判断,由于是ACTION_DOWN,继续进入1995行,继续进入2007行,继续进入2016的for循环,进入2049的条件判断。进入dispatchTransformedTouchEvent()方法,在该方法的2405行,handled = child.dispatchTouchEvent(event),也就是调用了MFramelayout的dispatchTouchEvent()方法,由于假定条件下其返回false,dispatchTransformedTouchEvent()该方法返回false,这样就不会进入2049行的条件。然后进入到2090的条件判断,还是调用了dispatchTransformedTouchEvent()方法,然后执行super.dispatchTouchEvent(event),也就是执行View.dispatchTouchEvent()方法。关于View.dispatchTouchEvent(),请查看郭霖的博客。在OFramelayout的onTouchEvent中返回true,则2092行的handled为true,那么OFrameLayout的dispatchTouchEvent返回true。
接下来触摸事件是ACTION_MOVE,进入到OFrameLayout的dispatchTouchEvent()方法。进入到1968行,intercepted = true,则不会进入1985的条件判断,接下来进入2090行的条件判断。在这个过程中,OFrameLayout没将事件传给子视图。也就是dispatchTouchEvent()方法在ACTION_DOWN时返回false,则收不到后续的触摸事件,在这里就是MFramelayout收不到后续事件。
结论2研读:
查看郭霖的博客。Android事件分发机制完全解析,带你从源码的角度彻底理解(上),
Android事件分发机制完全解析,带你从源码的角度彻底理解(下)
结论3研读
情况一:OFramelayout的onInterceptTouchEvent返回true。
OFrameLayout的dispatchTouchEvent()接受触控事件,ACTION_DOWN时会执行1960-》2092。mFirstTouchTarget为null,其赋值在2065行的addTouchTarget()方法中。ACTION_MOVE时执行1968-》2092。所以,在一次触摸事件中,如果onInterceptTouchEvent()中返回true,则触摸事件由该视图消费,不会再派发。
情况二:OFramelayout的onInterceptTouchEvent返回false。
ACTION_DOWN时,执行1960-》1985-》1995-》2049,假设子视图消费了事件并返回了true,则会执行2065行,则mFirstTouchTarget被赋值为该子视图。
ACTION_MOVE是,在上面假设下,mFirstTouchTarget不为空,则会调用onInterceptTouchEvent()方法。执行顺序1960-》1985,由于是ACTION_MOVE,则不会进1995,接下来到2097-》2106,然后执行子视图(MFramelayout)的dispatchTouchEvent()方法。
如果子视图没有消费事件,则mFirstTouchTarget为空,则onInterceptTouchEvent()只会执行一次。
所以onInterceptTouchEvent()返回false,会被一直调用(前提条件是子视图消费了事件并返回了true)。
情况三:在一次触摸事件中,OFramelayout的onInterceptTouchEvent返回false,在某个条件再返回true。
在OFramelayout的onInterceptTouchEvent返回false时,详情参考情况二。在某个条件下onInterceptTouchEvent返回true时,假设先前子视图消费了事件并返回了true(即mFirstTouchTarget不为空),会执行1960-》2097-》2375-》2112,在2112行mFirstTouchTarget被赋值为null。触摸事件继续执行1968-》2092,onInterceptTouchEvent不会再被调用。
所以如果onInterceptTouchEvent()先返回false,然后在某个条件返回true,则在起初返回false时,onInterceptTouchEvent()会被一直调用(前提条件是子视图消费了事件并返回了true),返回true后,onInterceptTouchEvent将不会再被调用,不管以后返回啥,onInterceptTouchEvent都不会再被调用。
ViewGroup的dispatchTouchEvent源码
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 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;
}
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;
}