先前分析了View的事件分发机制,但是现在的APP应用界面上的东西可不少,都是很多布局相互嵌套的,可不是只有几个孤零零的View而已,比如各种SlidingMenu侧滑控件以及ListView上下滑动控件,所以分析ViewGroup中的事件分发机制也是必不可少的,废话不多说,下面立刻开始。
代码测试
结合之前的代码,我加了一个自定义LinearLayout,重写它的dispatchTouchEvent方法、onIntercetTouchEvent方法和onTouchEvent方法,这三个方法是有关于事件分发的。
public class MyLayout extends LinearLayout{
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v("EventTest", "dispatchTouchEvent(MyLayout) ");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("EventTest","onTouchEvent (MyLayout)");
return super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.v("EventTest","onInterceptTouchEvent (MyLayout)");
return super.onInterceptTouchEvent(ev);
}
}
同时在布局文件中,将上次的自定义Button放到这次的自定义布局中,同时在activity中增加layout的处理代码以及重写了activity的dispatchTouchEvent和onTouchEvent方法。
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.v("EventTest","onTouch (MyLayout)");
return true;
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("EventTest", "onClick");
}
});
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.v("EventTest","onTouch(MyButton)"+event.getAction());
return false;
}
});
……
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v("EventTest","dispatchTouchEvent (activity)");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("EventTest","onTouchEvent (activity)");
return super.onTouchEvent(event);
}
为了方便,我再次把自定义Button的代码也贴出来
public class MyButton extends Button {
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyButton(Context context) {
super(context);
}
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.v("EventTest", "dispatchTouchEvent(MyButton) ");
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("EventTest", "onTouchEvent(MyButton) ");
return super.onTouchEvent(event);
}
}
运行程序,点击一下按钮,结果如下:
通过日志可以看到,事件传递从activity开始,进而执行了layout的dispatchTouchEvent方法,可以看到,事件分发是从activity先到viewgroup的,然后在layout中,执行了onInterceptTouchEvent方法,再然后却直接执行了MyButton的dispatchTouchEvent方法,而layout的ontouch方法和onTouchEvent方法却没有执行,为什么呢,从过程上看,问题应该在onInterceptTouchEvent上,按字面意思看,这个方法是拦截的意思,而从结果看,事件传递到了Button(从ViewGroup传到了View)里面,说明layout并没有拦截, onInterceptTouchEvent的默认返回值我们不知道是什么,但是可以尝试一下返回true会是什么样,改动代码,重新运行:
可以看到,拦截之后,事件成功的传递到了layout上面的ontouch事件,不知道大家有没有注意到一个细节,就是onInterceptTouchEvent方法只在down事件的时候执行了一次,后面并没有再次执行。而上面的结果却是onInterceptTouchEvent执行了三次(因为执行了1次move事件)这个先记下来等等分析。通过这次测试,大致可以判断viewgroup的onInterceptTouchEvent方法默认返回的应该是false,这里不再演示了,下面结合源码看看为什么会出现这种情况。
源码分析
首先需要知道,事件传递是从activity开始的,这点从前面就可以看到,每次事件都是从activity的dispatchTouchEvent方法开始的,所以先来看看activity的dispatchTouchEvent方法源码,看看里面执行了什么:
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
代码不多,首先第一个if语句判断了当事件是down的时候,就是最开始的时候,执行onUserInteraction方法,点进去看看
public void onUserInteraction() {
}
显然这是一条空方法,是让子类去实现的,由于这个方法在事件分发之前调用,所以可以通过实现这个方法,来知道当activity正在运行的时候用户是怎么和设备进行交互的,由于这个方法并没有返回值,所以对整个流程没什么影响,不要在意这些细节。。。。
继续看代码,第二个if语句里面判断,getWindow().superDispatchTouchEvent()这个可以肯定就是重点了,分发应该就是在这里进行的,首先第一个getWindow(),这是个什么鬼,通过方法名字可以判断应该获取一个window,点进去看看,确实是获取了一个Window,然后window继续调用superDispatchTouchEvent()方法,点开window类,却发现这个是一个抽象类,当然这个方法就是个抽象方法了,那么就要找到window类的实现类才行,执行过程肯定在那里,通过Window类源码的注释可以知道,window的实现类是PhoneWindow。
进PhoneWindow里面看看对应的方法
public boolean superDispatchKeyEvent(KeyEvent event)
{
return mDecor.superDispatchKeyEvent(event);
}
代码很简单,就是调用了mDecor的相应方法,这个mDecor又是个什么鬼,继续看
public final View getDecorView()
{
if(mDecor == null)
installDecor();
return mDecor;
}
installDecor()方法里面又会执行 generateDecor(),藏的好深,继续看
protected DecorView generateDecor()
{
int flags = getAttributes().flags;
boolean coverStatusBar = true;
if(getContainer() != null)
coverStatusBar = false;
else
if((flags & 0x10) == 0 || (flags & 0x80) != 0)
coverStatusBar = false;
return new DecorView(getContext(), -1, coverStatusBar);
}
这里会发现,这其实就是个DecorView,而
DecorView是一个内部类,继承了FrameLayout,就是说这是一个ViewGroup,是
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
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;
}
// 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 View[] children = mChildren;
final boolean customOrder = isChildrenDrawingOrderEnabled();
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder ?
getChildDrawingOrder(childrenCount, i) : i;
final View child = children[childIndex];
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
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();
mLastTouchDownIndex = childIndex;
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
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;
}
代码还是有点长的,不过不要在意那些细节。。。。关注流程即可,看21行,有个布尔类型的intercepted,可以看到,当viewgroup在两种情况下会判断是否进行拦截,一种是当事件类型为Action_down的时候,二是当mFirstTouchTarget!=null的时候,mFirstTouchTarget是个啥玩意儿,这个暂且先留着,继续看,下面有一个布尔类型的disallowIntercept,这个的意思就是禁止拦截,默认是false,这个标记位可以在子View中通过requestDisallowInterceptTouchEvent方法来设置,设置之后ViewGroup就无法拦截除了down事件外的其他事件,为什么说是除了down事件呢,因为前面第12行,当事件是down的时候,就会进入resetTouchState方法,这个方法中会重置标记位。所以面对down事件的时候,ViewGroup总会调用onInterceptTouchEvent来询问自己是否要拦截。进入if块中,发现执行了onInterceptTouchEvent方法,进入这个方法看一下:
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}
这方法相当简单,就是直接返回了false,证实了之前的推测,ViewGroup默认是不拦截事件的,继续往下看,发现一个canceled,这个又是啥,这个其实就是事件被取消,这个不常见(比如一个ViewGroup中包含了一个View,在down事件传递的时候,ViewGroup不拦截,View处理了down事件返回了true,但是当move事件传递过来的时候,ViewGroup拦截了,这时候ViewGroup的onTouch和onTouchEvent被触发,在触发之前View的dispatchTouchEvent就会收到ACTION_CANCEL事件,了解一下即可)。继续看,如果事件不被取消并且不被拦截的时候,进入if块中,第66行,遍历子元素,判断子元素是否可以接收到点击事件,主要判断两点,一个是子元素是否有动画在播放,还有就是点击事件的坐标是否在子元素的View区域内,如果条件满足就会交给子元素处理,下面有个dispatchTransformedTouchEvent方法,进去看看
/**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}
// 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);
}
// Perform any necessary transformations and dispatch.
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);
}
// Done.
transformedEvent.recycle();
return handled;
}
当child是空的时候,执行的就是super.dispatchTouchEvent()方法,如果child不为空,执行的就是child.dispatchTouchEvent(),这样就将事件传递到子元素View中了。下面继续看,有个addTouchTarget()方法,进去瞧瞧
/**
* Adds a touch target for specified child to the beginning of the list.
* Assumes the target child is not already present.
*/
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
这里会将mFirstTouchTarget赋值,也就是说如果子元素处理了事件,那么mFirstTouchTarget就不会是空,如果viewgroup拦截了事件,那么mFirstTouchTarget就会是空,所以刚才测试的结果是down事件的时候执行了onInterceptTouchEvent方法,并且返回了true,使得viewGroup拦截了事件,那么在move和up事件的时候,mFirstTouchTarget为null, onInterceptTouchEvent方法就不会被调用;如果onInterceptTouchEvent返回了false,那么viewGroup不拦截事件,子元素会处理事件,mFirstTouchTarget被赋值,所以onInterceptTouchEvent会每次都执行。
如果遍历了所有的子元素后事件都没有被处理完毕,包含两种情况,第一就是没有子元素,第二就是子元素处理了事件,但是在最后返回了false,那么这时候ViewGroup就会自己处理事件,看110行,注意第三个参数是null,经过前面的分析,这时候会执行super.dispatchTouchEvent方法,ViewGroup的super就是View,所以事件就会交给View的dispatchTouchEvent方法来处理。
而如果顶级ViewGroup的dispatchTouchEvent方法最后也返回了false,那么根据activity中dispatchTouchEvent方法的源码来看,最后就交给了activity的onTouchEvent方法来处理。这样,整个ViewGroup的事件分发流程执行了一次。
总结
1、viewGroup默认不拦截任何事件,但是如果拦截了事件,那么此次事件序列中的后续其他事件就会交给viewGroup处理,并且onInterceptTouchEvent不会被再次调用;如果没有拦截事件,那么每次事件传递的时候,onInterceptTouchEvent都会被调用。2、和ViewGroup相比,View没有onInterceptTouchEvent方法,一旦事件传递过来,那么View的onTouchEvent方法就会被调用(或者onTouch)
3、事件传递过程是从外向内的,事件总是先传给父元素,然后再分发给子元素,在子元素中可以通过requestDisallowInterceptTouchEvent方法干预父元素的分发过程,除了ACTION_DOWN事件。
图示
走过路过的朋友,欢迎留言指出不足,一起探讨,共同进步。