前言
在前面的文章中分析过了android的View的事件传递机制—android事件传递机制—源码分析(上) 。那么这篇文章我们就来分析android中的ViewGroup的事件传递机制。
ViewGroup的事件传递机制
ViewGroup是View的子类,重写了View的dispatchTouchEvent方法,以便支持各种嵌套布局和子view。
同样的,我们先做一个简单的demo,定义一个自定义layout,内部放两个button。
<?xml version="1.0" encoding="utf-8"?>
<pg.com.mylibrary.MyLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mylayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pg.com.mylibrary.MainActivity">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕2" />
</pg.com.mylibrary.MyLayout>
public class MyLayout extends LinearLayout {
public MyLayout(Context context) {
super(context);
}
public MyLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
package pg.com.mylibrary;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "ph";
Button btn1;
Button btn2;
MyLayout myLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
myLayout = (MyLayout) findViewById(R.id.mylayout);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "btn1---onClick: ");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "btn2---onClick: ");
}
});
myLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "onTouch: ---mylaoyout");
return false;
}
});
}
}
现在我们分别点击button1,button2和空白的layout区域,控制台log如下:
也就是当点击按钮的时候,MyLayout的touch事件没有触发,而点击空白区域的时候,MyLayout的touch事件会触发。
看到这里你可能会觉得,事件会先被view拦截,view决定是否分发下去,那么我们接着往下看:
ViewGroup有一个onInterceptTouchEvent方法,我们点进去可以看到源码:
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}
我们再在自定义的myLayout实现这个方法,分别设置为true和false,看看有什么反应。当设置为false时,和上面的一样,从源码也可以看到if语句块里的条件非常难触发,一般正常的点击操作默认是返回false的。再将这个方法返回true,分别点击两个按钮和空白区域,控制台log结果如下:
可以看到,全部打印的都是layout的onTouch事件的触发。其实这个方法是ViewGroup判断是否拦截事件的方法,也就是说,其实事件是先分发到ViewGroup,ViewGroup再决定要不要分发给View的。那么我们再看ViewGroup的dispatchTouchEvent方法。
ViewGroup的dispatchTouchEvent源码
public boolean dispatchTouchEvent(MotionEvent ev) {
...//省略
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) {
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) {
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
...//省略
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;
}
// 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;
}
}
return handled;
}
源码省略了部分,可以看到仍然是很长。不过没关系,还是那句话,我们抓住重点,顺藤摸瓜,就一定能找到我们要找的答案。
首先我们可以看到一开始声明了一个变量 boolean handled = false;
并且最终的返回值是这个handled,表示该次事件分发是否被消费了。接着往下看:
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 = 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;
}
// 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;
}
}
}
这里定义了一个intercepted的布尔型变量,disallowIntercept表示是否禁用拦截功能,默认为false,所以通常是通过onInterceptTouchEvent方法赋值,默认在通常情况下也是返回false,子类可以通过重写该方法的返回值来决定是否拦截事件。返回true则表示拦截该事件。那么我们关注点跑到这个intercepted变量上来,接着往下看:
if (!canceled && !intercepted) {
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
...//省略
可以看到,一个大的条件,当!canceled && !intercepted两个条件同时成立的时候,才会进入这个判断,这是一个大的if语句块,那么接着在if语句块里面看:
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
...//省略
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,并且事件的在View还是ViewGroup中分发的决策在dispatchTransformedTouchEvent方法里面,可以看到第5行,如果该方法返回ture,则在语句块的最后会break终止循环,不再继续遍历。我们可以猜测,也就是说有对应的view或者ViewGroup自己决定处理的时候,才会返回true。这里要注意的还有两个地方:alreadyDispatchedToNewTouchTarget,newTouchTarget,这个和后面的代码有关系。
ViewGroup中分发的决策
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;
}
可以看到,这是一个私有方法,其实这个方法内部,看来看去,其实就是一个逻辑
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
不管什么不同的情况下 ,基本上都是这样的逻辑,如果传入的view为空,则调用super.dispatchTouchEvent,否则调用child.dispatchTouchEvent方法。我们记得ViewGroup是View的子类,所以super,其实就是调用View的dispatchTouchEvent方法,也就是之前那一篇的逻辑。也就是:逻辑相同,对象不同。这么说不知道好不好理解,总之在这里面,不管是ViewGroup还是View都统一看成View好了。那么经过这一步,就是执行完了对View及其一系列事件的分发,我们不管这里的View是button还是MyLayout,总之,当事件没有被拦截的时候,view的dispatchTouchEvent执行完毕,但是我们的ViewGroup的dispatchTouchEvent还是需要返回值来决定接下来怎么执行的。
我们出了 if (!canceled && !intercepted)的语句块接着往下看:
// 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);
上面的注释很清楚,当没有触碰目标的时候,将ViewGroup对待为View,handler的值为dispatchTransformedTouchEvent的返回值。也就是没有view会处理该次事件,交给ViewGroup来做。否则执行下面的代码:
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;
}
}
这里会遍历mFirstTouchTarget链表,一个一个地处理TouchTarget。可以看到两个条件:if (),这是上面提醒大家要注意的地方,在上面的if (dispatchTransformedTouchEvent)的条件判断中为true时,会给这两个关键的变量赋值:
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
那么这里的addTouchTarget方法又是什么呢?
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
public static TouchTarget obtain(@NonNull View child, int pointerIdBits) {
if (child == null) {
throw new IllegalArgumentException("child must be non-null");
}
final TouchTarget target;
synchronized (sRecycleLock) {
if (sRecycleBin == null) {
target = new TouchTarget();
} else {
target = sRecycleBin;
sRecycleBin = target.next;
sRecycledCount--;
target.next = null;
}
}
target.child = child;
target.pointerIdBits = pointerIdBits;
return target;
}
可以看到,代码如上:一开始sRecycleBin为null,所以obtain直接返回一个new TouchTarget对象,然后在addTouchTarget方法里,将mFirstTouchTarget设置给target.next。然而在这之前,mFirstTouchTarget一直没有赋值,也就是说mFirstTouchTarget=null,也就是target.next=null。最后将mFirstTouchTarget赋值为target,将这个target返回并赋值给newTouchTarget对象。也就是说在上面的while循环中:由于将mFirstTouchTarget设置给target返回给了newTouchTarget对象,所以,mFirstTouchTarget.next==null成立,也就是只进入一次循环,这次循环中,if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget)条件成立,将handler设置为true并跳出循环,最后作为ViewGroup的返回值。
可以发现,这里其实很妙,为什么呢,注意到这里拦截起的作用,其实你几乎感觉不到,但是正是因为一个判断条件, if (!canceled && !intercepted),也就是这个判断条件起的作用,如果没被拦截的话,那么巧妙地给newTouchTarget和mFirstTouchTarget设为相等并将next设为null,并将alreadyDispatchedToNewTouchTarget=true,使得进入下面的else条件的时候,不会进入dispatchTransformedTouchEvent方法,即使进入,child也为null,这样调用的就还是按照不拦截的事件分发了,而如果设置为拦截,则上面大条件里的代码就不会执行,那么mFirstTouchTarget==null恒成立,那么就只会进入一个条件执行一个条件里的代码:
// 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);
}
这样的话,由于传进去的child为null,那么也不会执行子view的dispatchTouchEvent方法,从而巧妙地将事件拦截了。
结语
上下两篇事件传递机制就先告一段落了,要学习的东西还有很多,但是每个知识点还是弄得相对透彻一点才好,我觉得学习android,除了参阅书籍和官方提供的api,最能弄明白一些原理的就是源码了,后续还是会多读framework层和一些优秀的开源框架的源码,和大家一起分享,很晚了,该睡了,晚安~