Android的事件分发机制是一个很重要的知识点,也是基础知识里相对比较难的一个知识点,但是其用途还是很广泛的,比如,在自定义view里或者解决滑动嵌套(其实google官方是不支持滑动嵌套的方式的,但是实际项目中还是有很多这种**的设计的)的时候。
理解事件分发的机制首先要理解三个方法:
- boolean dispatchTouchEvent (MotionEvent ev)
官方文档上解释很简单就就一句话,分发事件到目标视图,返回结果是boolean类型的,表示是否消耗该事件,返回true表示事件会被处理,否则相反。其结果受当前view的onTouchEvent和下级view的dispatchTouchEvent的影响。
- boolean onInterceptTouchEvent (MotionEvent ev)
官网说的很清楚了,实现这个方法是为了拦截屏幕的触摸事件,其实这个方法是在dispatchTouchEvent内部调用的。当需要在onTouchEvent里实现相对复杂的交互时可以使用这个方法。dispatchTouchEvent返回true的话,表示一整个事件系列都只能交给这个view来处理了,而且dispatchTouchEvent不会也没有必要再调用了。一旦这个view开始处理事件了,那么它必须消耗掉down事件,也就是说onTouchEvent必须返回true,否则的话这一事件序列的其它剩余事件就不会接受到了,事件会重新交给父元素去处理。类似与如果上级交给你一件事,你没有做好,那么同类的事上级短期内是不会再交给你的。
- boolean onTouchEvent (MotionEvent ev)
这个方法官网描述也比较简单,主要是处理触摸事件,分发onClickListener回调方法。需要注意的是,如果这个方法返回true表示这个事件被消耗掉了,否则这个事件不会再接受到同序列的其它事件,并且事件最终会回到上级去处理。另外,还需要注意的一点是在view中,onTouchListener的优先级要比onTouchEvent要高,而OnClickListener的优先级确实最低的,处于事件传递的末尾。如果view中设置了onTouchListener,事件的处理还得看onTouchListener的回调函数onTouch的返回值了,返回值是false的话onTouchEvent就被调用,否则不会调用。
至于这三者的关系其实网上的到处都有说,但是我觉得最简洁明了的还是一段伪代码:
public boolean dispatchTouchEvent(MotionEvent ev){
boolean consume = false;
if (onInterceptTouchEvent(ev)){
consume = onTouchEvent(ev);
}else {
consume = child.dispatchTouchEvent(ev);
}
return consume;
}
当点击事件产生后,首先会调用dispatchTouchEvent,如果onInterceptTouchEvent返回true表示他要拦截事件,接着onTouchEvent就会被调用。如果onInterceptTouchEvent返回false ,那么表示当前view不会拦截事件,那么这个事件就会继续传递到子view,于是,子view的dispatchTouchEvent方法调用,一直反复直到事件被处理。
接下来,看看源码中的事件处理吧:
点击事件发生时,首先传递到activity,然后acitivty在分发。
/**
* 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);
}
activty把事件交给了Window来分发,如果返回true则事件到此为止了,否则就是此事件子view都没有处理,又交给activty的onTouchEvent来处理了。
我们再看Window的唯一的实现类PhoneWindow的事件分发方法。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}```
可以看到事件继续交给了顶层View DecorView了,顶层布局一般都是ViewGroup,DecorView也不例外,其实它的实现类是继承于FrameLayout的。我们按住shift键继续往里点击。可以看到ViewGroup里的dispatchTouchEvent方法。
源码太长了,这里只贴出一部分,在2206~2221行的这一段代码里主要是判断事件是否会被拦截。
// 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;
}
由上面可以看出只有在down事件和mFirstTouchTarget != null时才需要判断,否则事件都是要拦截的。mFirstTouchTarget是"接受触摸事件的View"所组成的单链表,一旦ViewGroup子元素成功处理事件时mFirstTouchTarget就会被赋值。也就是说,只要当前ViewGroup不拦截事件那么 mFirstTouchTarget就不会为空。
当Viewgroup不拦截事件时,事件将会交给它的子view来处理
// 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;
}
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;
}
遍历子元素,如果事件的坐标是在子元素的区域内或者子元素在播放动画,那么子元素就能够接受收事件
跟进dispatchTransformedTouchEvent方法:
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;
}
child不是null时,事件就交给子 view的dispatchTouchEvent来处理了。现在我们来看看view 的dispatchTouchEvent源码:
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;```
view 无需再向下传递事件了,所以只能自己处理了。源码中,首先会判断OnTouchListener是否为null。如果onTouch方法返回true,那么onTouchEvent方法便不会调用。因此可见OnTouchListener的优先级还是高于onTouchEvent的。
看源码很累啊。。。。。。
分析参考《Android开发艺术探索》
网友评论