从点击屏幕开始,就会产生从Activity到DecorView然后一直到最里层的View的一系列事件及传递过程,每一层View或者ViewGroup都有可能会拦截或消费该事件,通过调用它的dispatchTouchEvent方法来判断,是否在当前View层消费该事件
View的事件分发,首先从一段伪代码上来看(个人觉得最简洁的事件分发总结,代码来自《Android开发艺术探索》):
public boolean dispatchTouchEvent(MotionEvent event) {
boolean isConsume = false;
if (isViewGroup) {
if (onInterceptTouchEvent(event)) {
isConsume = onTouchEvent(event);
} else {
isConsume = child.dispatchTouchEvent(event);
}
} else {
//isView
isConsume = onTouchEvent(event);
}
return isConsume;
}
从以上伪代码看出,如果当前是ViewGroup层级,就会判断该ViewGroup的onInterceptTouchEvent方法是否为true,如果为true,则代表事件要在这一层消费,不再向下传递,接着就会回调它的onTouchEvent方法;如果为false,则代表事件还要继续向下一层传递,继续传递到下一层并调用下一层的dispatchTouchEvent方法,接着同上一个一样的逻辑,一直传递到最里面一层的view。
以上,就是事件的分发流程。
接着,还没完呢,接下来是消费的过程。
当事件传递到View的onTouchEvent方法时,再由当前View来判断是否要消费,通过onTouchEvent方法的返回true和false来表示当前view是否消费此事件,如果返回为true,则代表消费了此事件,
伪代码如下:
public void handleTouchEvent(MotionEvent event) {
if (!onTouchEvent(event)) {//当前view的onTouchEvent为false,不消费此事件,取反,调用父view的onTouchEvent
getParent.onTouchEvent(event);
}
}
如果view的onTouchEvent返回false,那么就会调用它的父view的onTouchEvent,如果父view的onTouchEvent也返回false,
就会一层一层向上调用,一直到最上层也就是Activity的onTouchEvent方法被调用。
以上,消费流程完毕。
下面看看onTouchEvent,onTouch,onClick的调用关系:
伪代码如下:
public void consumeEvent(MotionEvent event) {
if (setOnTouchListener) {
onTouch();
if (!onTouch()) {
onTouchEvent(event);
}
} else {
onTouchEvent(event);
}
if (setOnClickListener) {
onClick();
}
}
当某一层view的onInterceptTouchEvent方法被调用,则代表要消费事件,如果设置了onTouchListener方法的话,onTouch()会被调用。如果onTouch()返回true,则不会调用onTouchEvent了;如果onTouch()返回false或者没有设置onTouchListener方法,则继续调用onTouchEvent方法。
一个触摸事件,首先是传递到Activity层级,然后传递到根view,通过一层一层的ViewGroup最终到处理的view,所以我们来一层一层解析
#Activity(dispatchTouchEvent)
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public void onUserInteraction() {
}
从上面可以看到,onUserInteraction是空方法,主要是调用到了上面的getWindow().superDispatchTouchEvent(ev),
返回true,则代表消费了事件,返回false,则代表下层没有view处理,就会直接走到activity的onTouchEvent方法。
接着看superDispatchTouchEvent方法,会走到PhoneWindow的superDispatchTouchEvent方法,然后会调用
DecorView的superDispatchTouchEvent,看代码:
#Window.java Window是一个抽象类,唯一的子类是PhoneWindow
public abstract boolean superDispatchTouchEvent(MotionEvent event);
#PhoneWindow.java
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
#DecorView.java
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
#DecorView的super类是ViewGroup.java,就会走到ViewGroup的dispatchTouchEvent方法中去
从上面代码中可以看到,依次经过了PhoneWindow到达了DecorView,DecorView是activity的根view,也就是setContentView
所设置的view的父view,继承自FrameLayout。而FrameLayout的父类其实是一个ViewGroup,也就会走到ViewGroup的
dispatchTouchEvent方法中去了。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
// Check for interception. 表示是否拦截的字段
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//FLAG_DISALLOW_INTERCEPT标志位是通过requestDisallowInterceptTouchEvent来设置的
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;
}
// 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 {
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;
}
}
}
}
以上源码中查看部分关键代码,首先是两个条件:
actionMasked == MotionEvent.ACTION_DOWN
mFirstTouchTarget != null
如果满足以上两条件中的一个,才能继续走下去,执行onInterceptTouchEvent等方法,否则直接intercepted = true;表示拦截。
第一个条件很明显,表示当前事件为按下事件。第二个条件是字段,根据下面的代码得知,当后面有view消费掉事件的时候,这个
mFirstTouchTarget字段就会被赋值,否则就为空。
所以,当ACTION_DOWN事件时候,一定会执行到后面的代码。当其他事件来的时候,要判断当前ViewGroup是否消费了事件,
如果当前ViewGroup消费了事件,没有传递到子view,那么mFirstTouchTarget字段就为空,也就不会执行到后面的代码了。这
也就符合了之前的一种机制:某个view一旦开始拦截了,那么后续事件就全部交给它来处理了,也不会执行onInterceptTouchEvent方法了
但是,两个条件满足一个,就能执行到onInterceptTouchEvent了吗?不一定。这里看到还有一个判断条件,disallowIntercept。
这个字段是由requestDisallowInterceptTouchEvent方法设置的,主要用于滑动冲突,意思就是子view告诉父view它不想让父view拦截,
那么这时候当前父view就不要拦截了,直接返回false。ok,继续看源码,上面我们了解到,如果ViewGroup不拦截事件,就会传递给子view,那么是在哪里传递的呢?还是在dispatchTouchEvent方法中
if (!canceled && !intercepted) {
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
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 (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
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;
}
if (!child.canReceivePointerEvents()
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
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();
}
}
}
这里可以看到,进行了一个子view的遍历,其中,如果满足两个条件中的一个,就跳出,否则就执行dispatchTransformedTouchEvent方法
先看两个条件:
!child.canReceivePointerEvents()
!isTransformedTouchPointInView(x, y, child, null)
看代码:
protected boolean canReceivePointerEvents() {
return (mViewFlags & VISIBILITY_MASK) == VISIBLE || getAnimation() != null;
}
@UnsupportedAppUsage
protected boolean isTransformedTouchPointInView(float x, float y, View child,
PointF outLocalPoint) {
final float[] point = getTempPoint();
point[0] = x;
point[1] = y;
transformPointToViewLocal(point, child);
final boolean isInView = child.pointInView(point[0], point[1]);
if (isInView && outLocalPoint != null) {
outLocalPoint.set(point[0], point[1]);
}
return isInView;
}
从上面两个代码中可以看出,canReceivePointerEvents方法代表view是否可以接受点击事件,比如是否正在播放动画。
而isTransformedTouchPointInView方法表示点击事件的坐标是不是在这个view的区域上面。如果条件都满足,就执行到
dispatchTransformedTouchEvent方法了。
看下面的源码:
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;
}
}
这个方法就是执行了child的dispatchTouchEvent,也就是下一层view的dispatchTouchEvent方法,开始了事件的层级传递。
View(dispatchTouchEvent),到了view层级的时候,自然就执行的view的dispatchTouchEvent方法。源码如下:
public boolean dispatchTouchEvent(MotionEvent event) {
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;
}
这里可以看到,首先判断li.mOnTouchListener != null,如果不为空,就会执行onTouch方法。根据onTouch方法返回的结果,
如果为false,result就为false,那么onTouchEvent才会执行。这也符合上面所说的逻辑。最后再来看看view的onTouchEvent都做了什么事:
public boolean onTouchEvent(MotionEvent event) {
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
mIgnoreNextUpEvent = false;
break;
}
return true;
}
return false;
}
从上述代码可以得知,如果设置了CLICKABLE或者LONG_CLICKABLE,那么这个view就会消费事件,并且执行 performClickInternal()方法
然后执行到performClick方法,这个performClick方法就是触发点击的方法,内部执行了onClick。
public boolean performClick() {
// We still need to call this method to handle the cases where performClick() was called
// externally, instead of through performClickInternal()
notifyAutofillManagerOnClick();
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
其实,事件分发的主要应用就是为了解决滑动冲突的。
一般有两种解决方法:
外部拦截:从父view端处理,根据情况决定是否将事件分发到子view
内部拦截:从子view端处理,根据情况决定是否阻止父view拦截,关键方法就是requestDisallowInterceptTouchEvent方法
第一种方法,其实是在onInterceptTouchEvent方法里面进行判断返回true还是false,
第二种方法就用到了requestDisallowInterceptTouchEvent方法了,
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean intercepted = false;
//父view拦截条件
boolean parentCanIntercept;
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
intercepted = false;
break;
case MotionEvent.ACTION_MOVE:
if (parentCanIntercept) {
intercepted = true;
} else {
intercepted = false;
}
break;
case MotionEvent.ACTION_UP:
intercepted = false;
break;
}
return intercepted;
}
//父view.java
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
return false;
} else {
return true;
}
}
//子view.java
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
//父view拦截条件
boolean parentCanIntercept;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
if (parentCanIntercept) {
getParent().requestDisallowInterceptTouchEvent(false);
}
break;
case MotionEvent.ACTION_UP:
break;
}
return super.dispatchTouchEvent(event);
}
相对于外部拦截法,内部拦截法稍微有点复杂,还要重写父view的方法。这里分析下,为什么要去这么写:
父view ACTION_DOWN的时候,不能拦截,因为如果拦截,那么后续事件也就跟子view无关了
父view 其他事件的时候,要返回true,表示拦截。因为onInterceptTouchEvent方法的调用是被
FLAG_DISALLOW_INTERCEPT标志位所控制,所以子view需要父view拦截的时候,才会走到这个onInterceptTouchEvent方法中来,
那么这时候要保证方法中一定是要拦截的。
事件分发最后是交给onTouchEvent来处理的哦~~~
至此,事件的分发机制也就分析的差不多了。
事件序列是成组的,以ACTION_DOWN开头,以ACTION_UP或者ACTION_CANCLE结束。cancle取消事件是一组特殊的非人为的事件。如果父view的onInterceptTouchEvent返回为true,那么子view就会收到一个cancle事件,来取消掉他已经接收的消息。
例如:在一个滑动列表中,点击某个控件,先开始的时候,是控件的onTouchEvent返回true,当在手指上下滑动时候,当滑动超过一定距离,则滑动控件拦截了点击事件,这时候就要给点击事件一个cancle通知,这就是cancle事件