前面一篇文章和大家一起从源码的角度阅读了Android 中view事件分发的机制,相信看过的朋友,对view的事件分发已经有了比较深的理解了。
还没有阅读过的朋友请参考Android事件分发机制解析(一)
今天我们就一起在从源码(android24的源码)的角度去分析下ViewGroup的事件分发
我们先来了解ViewGroup是什么?和View 有什么区别?
先来看看源码中ViewGroup 的类继承结构,如下:
大家可以看到ViewGroup 是View的子类,所以ViewGroup也是一个View,只是ViewGroup中会包含很多子View和子ViewGroup的,android中所有布局的父类或者间接父类都是ViewGroup,例如结构图中可以看到的LinearLayout,FrameLayout都是继承子ViewGroup的。
大家已经知道了ViewGroup是个什么了,那我们就通过一个简单的列子来看看ViewGroup的事件分发流程吧。
首先我们自定义个RelativeLayout布局 和一个自定义的button,如下所示:
public class DylanViewGroup extends RelativeLayout {
private static final String TAG = "ViewGroupActivity";
public DylanViewGroup(Context context) {
super(context);
}
public DylanViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.e(TAG, "onInterceptTouchEvent--> RelativeLayout:" + ev.getAction());
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e(TAG, "onTouchEvent-->RelativeLayout:" + event.getAction());
return super.onTouchEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.e(TAG, "dispatchTouchEvent-->RelativeLayout:" + ev.getAction());
return super.dispatchTouchEvent(ev);
}
}
public class DylanView extends Button {
private static final String TAG = "ViewGroupActivity";
public DylanView(Context context) {
super(context);
}
public DylanView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.e(TAG, "dispatchTouchEvent: Button" + event.getAction());
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e(TAG, "onTouchEvent:Button " + event.getAction());
return super.onTouchEvent(event);
}
}
然后打开布局文件,在其中加入我们的布局文件和自定义button,如下:
<?xml version="1.0" encoding="utf-8"?>
<jetsen.com.dylanview.DylanViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_view_group"
android:layout_width="match_parent"
android:layout_height="match_parent">
<jetsen.com.dylanview.DylanView
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</jetsen.com.dylanview.DylanViewGroup>
紧接着,在Activity中给这个按钮和RelativeLayout布局添加监听事件:
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick-->RelativeLayout ");
}
});
relativeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e(TAG, "onTouch--> RelativeLayout:" + event.getAction());
return false;
}
});
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e(TAG, "onTouch-->Button" + event.getAction());
return false;
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick-->Button");
}
});
点击一下按钮以外的空白区域执行结果如下:
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent–>RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: onInterceptTouchEvent–> RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: onTouch–> RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: onTouchEvent–>RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent–>RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: onTouch–> RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: onTouchEvent–>RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: onClick–>RelativeLayout
点一下按钮执行结果如下:
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent–>RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: onInterceptTouchEvent–> RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent: Button0
jetsen.com.dylanview E/ViewGroupActivity: onTouch–>Button0
jetsen.com.dylanview E/ViewGroupActivity: onTouchEvent:Button 0
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent–>RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: onInterceptTouchEvent–> RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent: Button1
jetsen.com.dylanview E/ViewGroupActivity: onTouch–>Button1
jetsen.com.dylanview E/ViewGroupActivity: onTouchEvent:Button 1
jetsen.com.dylanview E/ViewGroupActivity: onClick–>Button
通过上面的执行结果我们也发现了点击按钮以外的空白区域,只执行了RelativeLayout 一些列事件,没有执行与Button 相关的事件,而点击Button 按钮的时候,执行了RelativeLayout 的dispatchTouchEvent,onInterceptTouchEvent,按下和抬起事件但是没有执行onTouch,onTouchEvent 的事件以及Button 的一些列事件。这是为什么那?
我们不妨先猜测如下结论:
1.android中的Touch事件先接触到的是父容器,然后有父容器像子View分发。
2ViewGroup中事件的执行顺序是dispatchTouchEvent–》onInterceptTouchEvent–》onTouch(return false)–》onTouchEvent–》onClick。
到这里,我们只有去看ViewGroup的源码才能才能知道我们猜测的结论是否正确了哈。
通过打印结果我们发现了和View的事件分发多了一个onInterceptTouchEvent 的事件?这个事件是干什么的那?我们先去看看它的源码:
/**
* Implement this method to intercept all touch screen motion events. This
* allows you to watch events as they are dispatched to your children, and
* take ownership of the current gesture at any point.
*
* <p>Using this function takes some care, as it has a fairly complicated
* interaction with {@link View#onTouchEvent(MotionEvent)
* View.onTouchEvent(MotionEvent)}, and using it requires implementing
* that method as well as this one in the correct way. Events will be
* received in the following order:
*
* <ol>
* <li> You will receive the down event here.
* <li> The down event will be handled either by a child of this view
* group, or given to your own onTouchEvent() method to handle; this means
* you should implement onTouchEvent() to return true, so you will
* continue to see the rest of the gesture (instead of looking for
* a parent view to handle it). Also, by returning true from
* onTouchEvent(), you will not receive any following
* events in onInterceptTouchEvent() and all touch processing must
* happen in onTouchEvent() like normal.
* <li> For as long as you return false from this function, each following
* event (up to and including the final up) will be delivered first here
* and then to the target's onTouchEvent().
* <li> If you return true from here, you will not receive any
* following events: the target view will receive the same event but
* with the action {@link MotionEvent#ACTION_CANCEL}, and all further
* events will be delivered to your onTouchEvent() method and no longer
* appear here.
* </ol>
*
* @param ev The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
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;
}
注释挺多的哈?不过代码没有几行,最后要返回一个true 和false 我们在自定义的RelativeLayout 布局中复写了这个方法默认调用的是super.onInterceptTouchEvent(ev) ,我们返回结果改成true 试试看有什么变化吗?
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent–>RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: onInterceptTouchEvent–> RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: onTouch–> RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: onTouchEvent–>RelativeLayout:0
jetsen.com.dylanview E/ViewGroupActivity: dispatchTouchEvent–>RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: onTouch–> RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: onTouchEvent–>RelativeLayout:1
jetsen.com.dylanview E/ViewGroupActivity: onClick–>RelativeLayout
发现不管是点击按钮还是按钮以外的空白处,打印的结果都如上所示,只有RelativeLayout 的相关事件了,Button 的事件不执行,由此可知道原来onInterceptTouchEvent这个方法就是拦截事件的方法哈,默认返回的是false 不拦截事件。
接下来我们要看看viewGroup的dispatchTouchEvent 的这个方法的源码了。看看他到底是何方神圣,是如何做到事件分发的。
源码如下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
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;
}
// 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) {
// 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;
}
}
}
// 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;
}
有点小多哈,看着比View的dispatchTouchEvent 事件复杂多了。确实复杂多了,不过呢我们依然是捡重点看,相信大家已经熟悉了一个看源码的套路了,那就是捡重点看。
在第十四行大家可以看到一个变量 handled 默认是false, dispatchTouchEvent 最后返回的就是handled 这个变量,所以他肯定影响分发的流程,所以大家要记住这个变量,在31行有一个intercepted 的变量是在37行通过onInterceptTouchEvent(ev)这个方法赋值的,onInterceptTouchEvent这个方法在前已经说了就是拦截事件分发的,默认返回false 不拦截,走到这一行,并没有开启拦截的功能,拦截的功能是有intercepted 这个变量在64行的那个条件判断那里,如果返回的false,条件成立就会进去在143行有一个逻辑判断的条件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;
}
在16到21行之间,有没有发现新大陆的感觉哈,如果ViewGroup里面没有子控件就会执行super.dispatchTouchEvent(event)这个方法,viewGroup的父类是谁呢?由上面的类结构图可以知道它的父类就是View,所以后面的执行流程就和android事件分发机制(一)里面的一样了哈,那ViewGroup里面的子View不等于空就会执行child.dispatchTouchEvent(event)这个方法,但是如果child 为View的话就会执行View的事件分发流程,如果child 为ViewGroup的话,就又要执行ViewGroup的事件分发流程了,所以child.dispatchTouchEvent(event)就是一个递归调用。最后都会调用View的dispatchTouchEvent 这个方法。由此可以验证,我们上面的猜测是完全正确的哈。
在看下整个ViewGroup的事件分发流程图吧,相信可以帮助大家更好的去理解:
好了,今天就分析到这里,我们现在来总结下:
1. Android事件分发是先传递到ViewGroup,再由ViewGroup传递到View的。
2. 在ViewGroup中可以通过onInterceptTouchEvent方法对事件传递进行拦截,onInterceptTouchEvent方法返回true代表不允许事件继续向子View传递,返回false代表不对事件进行拦截,默认返回false。
3. 子View中如果将传递的事件消费掉,ViewGroup中将无法接收到任何事件。