android 的View事件的分发是android中的一个很重要的知识点,也是一个难点。
最近学习了一些与View有关的一些知识。所以做了下笔记,方便以后查阅。
接下来分析的是一个点击事件从被系统捕捉到分发到对应的对象的过程。
大体的思路可以用下面两个图来表示:
图一:点击事件先被其所在的activity捕捉,然后传递给其所在的window,再传到decorView,也就是顶级View
图二:顶级View到具体View的事件分发。
好了,整个过程大体就是这样了。
接下来我们具体来分析。
一、Activity接收到事件:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
我们从activity中的dispatchTouchEvent方法中可以了解到。这个方法先调用其所在Window的superDispatchTouchEvent方法,如果该方法返回true的话那么就整个方法结束。否则的话就调用activity的onTouchEvent方法。
二、Window将事件传递给了decorView。
public abstract boolean superDispatchTouchEvent(MotionEvent event);
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
// This is the top-level view of the window, containing the window decor.
private DecorView mDecor;
@Override
public final View getDecorView() {
if (mDecor == null) {
installDecor();
}
return mDecor;
}
三、ViewGroup拦截情况。
// 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;
}
然而这个方法的上面还有这么一段。
// 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();
}
如果是为Action_Down的话那么就会调用resetTouchState()方法,而这个方法将会重置FLAG_DISALLOW_INTERCEPT这个标位,也就是说子View设置的阻止拦截方法并不能拦截到ACTION_DOWN。
四、ViewGroup不拦截情况
假如ViewGroup不拦截呢?
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;
}
代码比较多,不过其中最主要的一句就是通过循环遍历子View,并且调用了dispatchTransfromedTouchEvent方法(31行),而这个方法在内部也会调用子元素的dispatchTouchEvent。
能被传递的子View需要具备以下两个条件。
1、该View没有在播放动画。
2、事件发生的位置为该View的位置。
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
......
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
......
return handled;
}
如果这个方法返回了true,那么就会执行上面循环中的几句代码(上面第47行):
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
从中我们就可以知道一旦遍历的子View中有方法返回true的话就会跳出循环,也就是说找到了那消费事件的View。其中addTouchTarget方法会将该子View的引用赋值给mFirstTouchTarget,这样的话下次就会直接将事件分发给他了。(后面跟着的事件是除了ACTION_DOWN外的事件),所以这个会影响着下次事件的分发。
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
五、ViewGroup不拦截,但是子View没能处理情况下。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
这样子的话就调用dispatchTouchEvent,但是传递进去后的child为null,这样的话就会调用super.dispatchTouchEvent方法,也就是调用View的方法。注意ViewGroup也是一种View。
六、具体View对事件的处理
事件如果成功传递到了具体的View的话,View就需要对其进行处理。
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
......
if (onFilterTouchEventForSecurity(event)) {
//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;
}
}
........
return result;
}
其中我们判断这个View有没有设置TouchListener,如果有的话就调用其onTouch方法,如果没有的话就调用onTouchEvent方法。如果两者并存的话,那么如果onTouch方法返回为true的话,就表示事件已经被其拦截,所以onTouchEvent方法就不能够执行了。反之,则两者都可以执行。
接下来我们进入onTouchEvent方法,其中有这么一段:
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
注意:不管一个View是enable 还是disable 只要其Clickable和LongClickable不同时为false,事件就会被它消费掉。
而我们对一个View设置clickListener和LongClickListener的时候就会改变这两个标志。
另外如果我们设置了代理mTouchDelegate的话,那么代理也会执行。
而在View的onTouchEvent方法中会调用perfromClick方法,在这个方法中又会调用我们设置的onClickListener等。
七、总结。
这是我写的第一篇文章。也是自己比较认真做的一些笔记。主要讲了一个点击事件的传递过程。
当一个点击事件发生后,首先会被其activity接受(一般情况),然后activity通过window委托给了decorView,然后decorView如果不拦截的话就会下传到其子View。DecorView就像是树根。下传任务给下属结点,如果下属结点能够完成,那么后序的一系列事务都由该View处理。如果全部处理不了就会上抛。最后传递回Activity。由Activity自己处理。