上一篇分析了Android事件分发机制源码分析之View篇 ,按照计划我们这篇分析一下关于ViewGroup的事件分发。
那么我们首先要清楚理解一下View和ViewGroup之间的关系,我选取LinearLayout为例子,我们看一下LinearLayout的继承关系:
从图中看出的继承关系是,LinearLayout是继承ViewGroup,而ViewGroup是继承View,View则是继承我们的所以类的基类Object。那就是说,我们平时使用的LinearLayout、RelativeLayout等等常用Layout都是继承ViewGroup的,Button、TextView是继承View的,但是ViewGroup实际也是一个View。那么我们现在结合一下Demo来分析一下ViewGroup事件分发源码。
示例代码
我们接着用回上一篇的CustomButton.class,本篇添加一个CustomLayout.class.
public class CustomLayout extends LinearLayout {
private static final String TAG = "CustomLayout";
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLayout(Context context) {
super(context);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "dispatchTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "dispatchTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "dispatchTouchEvent ACTION_UP");
break;
default:
break;
}
boolean b = super.dispatchTouchEvent(ev);
Log.i(TAG, "dispatchTouchEvent return " + b);
return b;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onTouchEvent ACTION_UP");
break;
default:
break;
}
boolean b = super.onTouchEvent(event);
Log.i(TAG, "onTouchEvent return " + b);
return b;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onInterceptTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onInterceptTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onInterceptTouchEvent ACTION_UP");
break;
default:
break;
}
boolean b = super.onInterceptTouchEvent(event);
Log.i(TAG, "onInterceptTouchEvent return " + b);
return b;
}
}
我是继承常用的LinearLayout,然后重写和打印部分事件分发代码。
然后看一下布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<com.example.pc.myapplication.CustomLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.pc.myapplication.CustomButton
android:id="@+id/button"
android:layout_width="100dip"
android:layout_height="100dip"
android:text="button" />
</com.example.pc.myapplication.CustomLayout>
</RelativeLayout>
一个充满屏幕的CustomLayout里面包含着一个固定宽高的CustomButton。直接编译运行我们的程序,看看打印台打印情况:
点击非按钮范围的Layout:
点击CustomButton按钮:
从上一篇的 Android事件分发机制源码分析之View篇 中我们说过在ViewGroup的分析中会涉及到onInterceptHoverEvent(),我可以从打印台中看出ViewGroup的事件分发的不同。现在我们从源码中,探究一下原因。
源码分析。依据Android API 23 Platform
我们按照打印台的打印顺序来先分析一个ViewGroup的dispatchTouchEvent()。由于源码过长,我们分段分析。
最开始第一步只是一些对View是否可以获得焦点的判断、设置标志位以及初始化一些布尔值,并且在ACTION_DOWN事件产生的时候清楚以外的状态并且准备开始新一轮的手势操作,不是我们的重要;我们看下面的代码:
···
// 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;
}
···
这里第二步设置一个intercepted的布尔值去判断当前ViewGroup是否要进行拦截事件,在后面的if条件中,第一个是判断是否按下事件,第二个是mFirstTouchTarget!=null,然而mFirstTouchTarget是什么呢?我们找一下涉及这个变量的代码。
private void cancelAndClearTouchTargets(MotionEvent event) {
if (mFirstTouchTarget != null) {
boolean syntheticEvent = false;
if (event == null) {
final long now = SystemClock.uptimeMillis();
event = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
syntheticEvent = true;
}
for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
resetCancelNextUpFlag(target.child);
dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
}
clearTouchTargets();
if (syntheticEvent) {
event.recycle();
}
}
}
···
···
/**
* Clears all touch targets.
*/
private void clearTouchTargets() {
TouchTarget target = mFirstTouchTarget;
if (target != null) {
do {
TouchTarget next = target.next;
target.recycle();
target = next;
} while (target != null);
mFirstTouchTarget = null;
}
}
从上面的源码可以看到,cancelAndClearTouchTargets()这方法是对mFirstTouchTarget的清空,这个方法也是在dispatchTouchEvent()的开头且是//Check for interception的判断之前的部分代码,这里我们知道了ViewGroup的dispatchTouchEvent()一开始是对mFirstTouchTarget的这个变量作一个置空处理的。那么mFirstTouchTarget的赋值呢?我们继续找:
/**
* Adds a touch target for specified child to the beginning of the list.
* Assumes the target child is not already present.
*/
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
好了,我们找到了mFirstTouchTarget的赋值部分,从它的封装的方法了解到是处理获得子View并赋值的。而为什么要有if(actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)这个判断的呢?这里解释一下,比如说,子View消耗了ACTION_DOWN事件,然后这里可以由ViewGroup继续判断是否要拦截接下来的ACTION_MOVE事件之类的;又比如说,如果第一次DOWN事件最终不是由子View消耗掉的,那么显然mFirstTouchTarget将为null,所以也就不用判断了,直接把intercept设置为true,此后的事件都是由这个ViewGroup处理。
我们回到//Check for interception的代码中的 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;第二个值是常量,第一个值在一开始的resetTouchState()有设置,同样我们可以对mGroupFlags变量的搜索可以找到public的设置方法requestDisallowInterceptTouchEvent()可以对mGroupFlags变量进行修改。看看它的源码:
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
// We're already in this state, assume our ancestors are too
return;
}
if (disallowIntercept) {
mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
} else {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
// Pass it up to our parent
if (mParent != null) {
mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
从方法名中我们看出它是请求不允许拦截触摸事件。在示例代码中我们也有重写这个方法,说明这个方法是可以设置我们的ViewGroup是否要拦截这个触摸事件的。如果没有重写去设置requestDisallowInterceptTouchEvent方法,那么程序就会继续往下走到调用onInterceptTouchEvent(ev)方法,我们找到这个方法:
/**
* 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) {
return false;
}
这里注释很长,但是代码就很短,就一个返回值,这里返回False,说明ViewGrup默认不拦截点击事件,事件可以继续往下传递。另外说明了在ViewGroup中,调用dispatchTouchEvent()–>onInterceptTouchEvent()的顺序。
接下来的第三步源码,是检测cancel,通过标记和action检查cancel,然后将结果赋值给局部boolean变量canceled。不是我们的重点。
继续走:
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
首先可以看见获取一个boolean变量标记split来标记,默认是true,作用是是否把事件分发给多个子View,这个同样在ViewGroup中提供了public的方法setMotionEventSplittingEnabled()设置,如下:
public void setMotionEventSplittingEnabled(boolean split) {
// TODO Applications really shouldn't change this setting mid-touch event,
// but perhaps this should handle that case and send ACTION_CANCELs to any child views
// with gestures in progress when this is changed.
if (split) {
mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
} else {
mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
}
}
第四步事件分发。
//如果没有取消当前动作并且ViewGroup未拦截事件,那么事件就传递到接收了该点击事件的View
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;
//是否ACTION_DOWN的事件
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;
//判断了childrenCount个数是否不为0
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.
//拿到了子View的list集合preorderedList
final ArrayList<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//倒序遍历所有的子view
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.
//寻找能够获得焦点的Children(View)
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//查找当前子View是否在mFirstTouchTarget.next这条target链中的某一个targe中,如果在则返回这个target,否则返回null。
//在这段代码的if判断通过说明找到了接收Touch事件的子View(消耗了这个Touch事件),即newTouchTarget,那么,既然已经找到了,所以执行break跳出for循环。
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);
//正常的如果找不到newTouchTarget,即是这个Touch事件还没有被子View消耗,有相应记录的TouchTarget,即调用dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)传递给子View,然后根据返回值去判断子View是否消耗的这个Touch事件
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();
//将接收这个事件的Child(View)赋值给mFirstTouchTarget,并将原来的mFirestTouchTarget给TouchTarget列表的下一个,并且跳出这个循环,因为事件被Child(View)消耗了,所以newTouchTarget依然也有值
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();
}
//该种情况是,如果事件不是ACTION_DOWN,mFisrtTarget就不会被重置为null,但是如果要newTouchTarget有值,必须是事件在Child(View)里面被消耗了,简单概括事件被分下去了,,却没被消耗,于是就把事件添加进最近的TouchTarget里面去了
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;
}
}
}
普通的代码注释我直接写在上面,我们重点开一下dispatchTransformedTouchEvent()。其实dispatchTransformedTouchEvent()将Touch事件传递给特定的子View,它实际上在内部是调用了子元素的disPatchTouchEvent方法,找一下它的源码:
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();
//传进来的cancel值为false且不是取消的动作,所以不执行这里的代码
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.
//如果子View为空就会调用View的dispatchTouchEvent方法去处理
if (child == null) { // 1
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());
}
//子View是ViewGroup就调用ViewGroup,如果子View是View就调用View的
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
看我标记了1的部分代码,如果传递的child为null就调用父类的dispatchTouchEvent否则就调用子类的dispatchTouchEvent,而上面的代码中child不为null,所以执行子元素的dispatchTouchEvent,这里完成了ViewGroup到子View的事件传递。验证了super.dispatchTouchEvent()–>onInterceptTouchEvent()–>child.dispatchTouchEvent()的顺序。
如果子元素的dispatchTouchEvent返回的是true,那么调用dispatchTransformedTouchEvent这个方法内部的for循环就不会继续下去,直接break跳出了循环,因为已经找到了处理事件的子View,那就无需继续遍历了。而代码将会执行如下:
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
这里的addTouchTarget()就是我们上面提及过的方法,因为这里一个子View能够消耗事件,那么mFirstTouchTarget会指向子View,
但是如果子元素的dispatchTouchEvent返回的是false,那么当前ViewGroup会把点击事件传递给下一个子元素进行处理,执行for循环查找下一个子元素。如果子View都不能消耗事件,那么mFirstTouchTarget将为null。
接着dispatchTouchEvent()的代码,这部分是非ACTION_DOWN的事件将从以下开始处理:
// 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);// 1
} 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)) {// 2
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
首先是一个if判断语句,判断mFirstTouchTarget是否为Null,如果为null,那么调用1处的代码:dispatchTransformedTouchEvent(ev,canceled,null,TouchTarget.ALL_POINTER_IDS),这个方法上面出现过了,这里第三个参数为null,那么我们看方法里面,会执行super.dispatchTouchEvent(event);这里意思是说,如果找不到子View来处理事件,那么最后会交由ViewGroup来处理事件。这里验证了一开始我们的实例代码,在点击非CustomButton的CustomLayout部分,只打印了CustomLayout的重写部分代码。接着,如果在上面已经找到一个子View来消耗事件了,那么这里的mFirstTouchTarget不为空,接着会往下执行。
接着有一个if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget)判断,这里就是区分了ACTION_DOWN事件和别的事件,因为在上面dispatchTransformedTouchEvent()返回true的情况分析我们知道,如果子View消耗了ACTION_DOWN事件,那么alreadyDispatchedToNewTouchTarget和newTouchTarget已经有值了,所以就直接置handled为true并返回;那么如果alreadyDispatchedToNewTouchTarget和newTouchTarget值为null,那么就不是ACTION_DOWN事件,即是ACTION_MOVE、ACTION_UP等别的事件的话,就会调用2的部分代码,把这些事件分发给子View。
上面就基本分析了ViewGroup的事件分发的基本流程走向,下面我们用一张图来理顺一下上面我们分析的源码。
图2
图形剖析
可能上面的源码分析,有部分同学还是不能清晰理解ViewGroup的事件分发,那么我们直接通过示例代码来理解。
- CustomLayout不拦截、CustomButton不消费;
我们的CustomButton不消费就是onTouchEvent返回false,看看打印情况。
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent ACTION_DOWN
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent ACTION_DOWN
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent return false
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent ACTION_DOWN
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/MainActivity: onTouch ACTION_DOWN
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/MainActivity: onTouch return false
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomButton: onTouchEvent ACTION_DOWN
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomButton: onTouchEvent return false
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent return false
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomLayout: onTouchEvent ACTION_DOWN
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomLayout: onTouchEvent return false
11-01 14:18:29.275 29088-29088/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent return false
- CustomLayout不拦截,CustomButton消费;
我们一开始的实例代码就是这个情况,我们可以再看看打印数据
11-01 14:15:47.361 16958-16958/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent ACTION_DOWN
11-01 14:15:47.361 16958-16958/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent ACTION_DOWN
11-01 14:15:47.361 16958-16958/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent return false
11-01 14:15:47.361 16958-16958/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent ACTION_DOWN
11-01 14:15:47.361 16958-16958/com.example.pc.myapplication I/MainActivity: onTouch ACTION_DOWN
11-01 14:15:47.362 16958-16958/com.example.pc.myapplication I/MainActivity: onTouch return false
11-01 14:15:47.362 16958-16958/com.example.pc.myapplication I/CustomButton: onTouchEvent ACTION_DOWN
11-01 14:15:47.364 16958-16958/com.example.pc.myapplication I/CustomButton: onTouchEvent return true
11-01 14:15:47.364 16958-16958/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent return true
11-01 14:15:47.364 16958-16958/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent return true
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent ACTION_UP
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent ACTION_UP
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent return false
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent ACTION_UP
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/MainActivity: onTouch ACTION_UP
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/MainActivity: onTouch return false
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomButton: onTouchEvent ACTION_UP
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomButton: onTouchEvent return true
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent return true
11-01 14:15:47.378 16958-16958/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent return true
11-01 14:15:47.384 16958-16958/com.example.pc.myapplication I/MainActivity: onClick Event
- CustomLayout拦截;
因为我们在CustomLayout的onInterceptTouchEvent的返回值设置为true,进行拦截,于是程序会走到CustomLayout的onTouchEvent(),而且不会去到CustomButton的onInterceptTouchEvent()。看打印数据:
11-01 14:19:42.615 30336-30336/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent ACTION_DOWN
11-01 14:19:42.615 30336-30336/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent ACTION_DOWN
11-01 14:19:42.615 30336-30336/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent return true
11-01 14:19:42.615 30336-30336/com.example.pc.myapplication I/CustomLayout: onTouchEvent ACTION_DOWN
11-01 14:19:42.615 30336-30336/com.example.pc.myapplication I/CustomLayout: onTouchEvent return false
11-01 14:19:42.615 30336-30336/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent return false
总结:
- 在是否拦截当前事件,返回true表示拦截,如果拦截了事件,那么将不会分发给子View。比如说:ViewGroup拦截了这个事件,那么所有事件都由该ViewGroup处理,它内部的子View将不会获得事件的传递。(但是ViewGroup是默认不拦截事件的)注意:View是没有这个方法的,也即是说,继承自View的一个子View不能重写该方法,也无需拦截事件,因为它下面没有View了,它要么处理事件要么不处理事件,所以最底层的子View不能拦截事件;
- 事件传递过程是由外向内的,即事件总是先传给父元素,然后再由父元素分发给子VIew,子View可以通过requestDisallowInterceptTouchEvent来干预父元素的分发过程,但是影响不到ACTION_DOWN事件;
- 如果ViewGroup找到了能够处理该事件的View,则直接交给子View处理,自己的onTouchEvent不会被触发;
- 子View可以通过调用getParent().requestDisallowInterceptTouchEvent(true); 阻止ViewGroup对其MOVE或者UP事件进行拦截;
下一篇我们来继续分析Android事件分发机制源码分析之Activity篇
参考文章: