Android笔记-Android事件分发机制之ViewGroup
先写一个Demo,新建一个MyLinearLayout继承于LinearLayout,新建一个MyButton继续于Button。分别在MainActivity,MyLinearLayout,MyButton中重写dispatchTouchEvent()方法。
在MyButton.java中的dispatchTouchEvent()添加日志,MyLinearLayout与MainActivity类似。
查看日志
事件传递方向:MainActivity–>MyLinearLayout–>MyButton
这里Activity–>ViewGroup,其实也是ViewGroup–>ViewGroup的过程,关于Activity里面mWindow ,PhoneWindow等知识并不打算在这里说,如不清楚,只需记得Activity最外层有一个FrameLayout,事件由FrameLayout传递给MyLinearLayout。这里重点说明ViewGroup如果将事件往内层传递。
结论1:事件由最外层的FrameLayout向内逐一传递。
修改代码给MainActivity,MyLiearnLayout,MyButton设置OnTouchEvent(),打印日志并返回true表示“消费”该事件。
查看日志
这里当MainActivity,MyLiearnLayout,MyButton的OnTouchEvent()中返回true的情况,只调用了MyButton中方法OnTouchEvent来处理事件,而MainActivity,MyLiearnLayout并没有执行。
修改MyButton中OnTouchEvent的返回值为false,MyButton不“消费”该事件。看到下面日志
当MyButton不“消费”事件的时候,只调用了一次dispatchTouchEvent,onTouchEvent,之后都调用MyLinearLayout中dispatchTouchEvent,onTouchEvent的方法。
再修改MyLinearLayout中OnTouchEvent的返回值为false。日志如下
MyButton,MyLinearLayout的OnTouchEvent执行了一次,返回false没有“消费”事件,之后事件全部交由MainActivity“消费”。
结论2:”消费”事件的优先级,内层控件高于外层控件,如果最内层控件不“消费”该事件,则查看父控件,逐一往上找
结论3:一般情况下,只能有一个控件来消费事件序列里面的所有事件,如果不“消费”down,在move或者up的时候,甚至不会调用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;
}
注:这里版本是23,本人不会引用代码,可能看起来比较混乱。
方法88-145行
用一个for循环,根据事件产生的x,y先找出相应的子View。如果子View是ViewGroup则调用ViewGroup的dispatchTouchEvent方法继续往下找,如果是View,则看dispatchTouchEvent的返回值。如果为返回值true,则表示该事件被“消费”,代码137行
newTouchTarget = addTouchTarget(child, idBitsToAssign);
addTouchTarget代码
通过addTouchTarget设置ViewGroup的成员变量mFirstTouchTarget,mFirstTouchTarget保存着被点击View和id。如果返回值为false,则继续在子View中寻找。比如FrameLayout有两个大小一样的Button,点击Button所在的位置,后添加的Button如果不“消费”事件,则会继续判断前一个Button是否“消费”事件。
代码88行
for (int i = childrenCount - 1; i >= 0; i--) {
关于结论1:ViewGroup会通过这个for循环找到被点击所在位置且能“消费”事件的子View来处理该事件序
如果在for循环中找到符合条件的子View
action_down:方法121行调用dispatchTransformedTouchEvent执行子View的onTouchEvent“消费”down事件,返回true,方法137行addTouchTarget设置mFirstTouchTarget != null,方法138行alreadyDispatchedToNewTouchTarget = true;方法162进入else,target != null,进入while循环,if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget)判断为true,最终跳出,结束action_down。
action_move:方法162mFirstTouchTarget不为null,进入else,将mFirstTouchTarget赋值给target,target不为null,方法173target == newTouchTarget为false,因为在方法55行,已经将newTouchTarget == null,方法178行执行dispatchTransformedTouchEvent判断事件是否“消费”。因为找到子View的onTouchEvent返回true所以,子View也会“消费”action_move。
action_up与action_move一致
如果在for循环中没有找到符合条件的子View
action_down:方法121行调用dispatchTransformedTouchEvent执行子View的onTouchEvent返回false,没有“消费”action_down。而每次action_down都会把mFirstTouchTarget设置为null,方法164调用dispatchTransformedTouchEvent,child参数为空,看到代码dispatchTransformedTouchEvent里面当child为null的时候,调用super.dispatchTouchEvent,调用ViewGroup方法处理该事件。
action_move:方法28行mFirstTouchTarget为null,action不是down,进入else intercepted = true,方法57行判断!intercepted为false,到162后处理与action_down类似,都是用父类ViewGroup来”消费”事件。
action_up与action_move一致。
这里如果ViewGroup的onTouchEvent返回false,将结果返回给上一级处理
关于结论2,3:由mFirstTouchTarget是否为空,来判断事件是否“消费”,由哪个控件消费
在上面的源码分析中,多次看到局部变量intercepted,intercepted用来表示是否拦截ViewGroup将事件分发给子View。intercepted可以由onInterceptTouchEvent(),mGroupFlags决定。如果在ViewGroup中代码中重写onInterceptTouchEvent(),返回true,表示拦截。
点击按钮
虽然MyButton的onTouchEvent返回true,可以“消费”事件,但onTouchEvent并没有被调用,甚至连dispatchTouchEvent都没有调用。看一下源码,方法32行onInterceptTouchEvent返回true,intercepted为true,方法57行为false没有进入去寻找合适x,y的子View,这样在action_down的时候mFirstTouchTarget为null,方法162行会dispatchTransformedTouchEvent,child参数为空,调用ViewGroup的onTouchEvent,而子View一直无法接收事件分发。
在子View中有一个方法可以使用getparent().requestDisallowInterceptTouchEvent(true),告诉父控件不要拦截事件。ViewGroup的requestDisallowInterceptTouchEvent方法实际上也是通过修改成员变量mGroupFlags来影响dispatchTouchEvent方法30行的disallowIntercept,通过disallowIntercept来改变intercepted,后面与intercepted分析是一致的。
最后关于requestDisallowInterceptTouchEvent和onInterceptTouchEvent写一个小Demo。在ViewGroup放置两个Button,一个MyButton只输出日志,没有做特殊处理。另一个MyButtonDisIntercept,在OnTouchEvent里面调用getParent().requestDisallowInterceptTouchEvent(true)。在ViewGroupmove和up事件的时候将onInterceptTouchEvent返回true,拦截事件分发。在Activity中对Button分别设置onClick监听器
MyLinearLayout.java部分代码
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean result = false;
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
Log.d("MotionEvent", "MyLinearLayout onInterceptTouchEvent ACTION_DOWN");
result = false;
break;
case MotionEvent.ACTION_MOVE:
Log.d("MotionEvent", "MyLinearLayout onInterceptTouchEvent ACTION_MOVE");
result = true;
break;
case MotionEvent.ACTION_UP:
Log.d("MotionEvent", "MyLinearLayout onInterceptTouchEvent ACTION_UP");
result = true;
break;
}
return result;
}
MyButtonDisIntercept.java部分代码
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.d("MotionEvent", "MyButtonDisIntercept onTouchEvent ACTION_DOWN");
// 请求父控件不要拦截
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
Log.d("MotionEvent", "MyButtonDisIntercept onTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.d("MotionEvent", "MyButtonDisIntercept onTouchEvent ACTION_UP");
break;
}
return super.onTouchEvent(event);
}
MainActivity.java部分代码
public void initView() {
mBtnMyButton = (MyButton) findViewById(R.id.my_button);
mBtnMyButtonDisIntercept = (MyButtonDisIntercept) findViewById(R.id.my_button_dis_intercept);
mBtnMyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MotionEvent", "mBtnMyButton onClick");
}
});
mBtnMyButtonDisIntercept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MotionEvent", "mBtnMyButtonDisIntercept onClick");
}
});
}
点击MyButton
点击MyButtonDisIntecept
通过日志可以发现MyButtonDisIntecept因为在onTouchEvent中调用getParent().requestDisallowIntecept(true),请求父控件不要拦截事件,最后执行onClick“消费”了该事件。这里有个注意点,就是requestDisallowIntecept(true)调用时机,因为ViewGroup在处理action_down的时候会重置mGroupFlags。