onTouch与onClick之间会产生事件冲突吗?
事件在控件中时如何传递的?
事件冲突的根本原因?
如何解决事件冲突?
View的事件分发机制
View的事件分发机制就是事件的传递过程,也就是一个Down事件,若干个Move事件,一个Up事件所构成的事件序列的传递过程。
当你手指按了屏幕,点击事件就会遵循Activity->Window->View这一顺序传递,所以如果所有的元素都返回了false,那么最后事件就会再次传递到Activity里,由Activity的onTouchEvent()方法来处理。
这一传递过程有三个重要的方法,分别是:
boolean dispatchTouchEvent(MotionEvent ev)
boolean onInterceptTouchEvent(MotionEvent event)
boolean onTouchEvent(MotionEvent event)
ViewGroup有dispatchTouchEvent()和onInterceptTouchEvent()方法,没有onTouchEvent()方法;
View有dispatchTouchEvent和onTouchEvent()方法,没有onInterceptTouchEvent()方法;
先简单介绍下这三个方法:
dispatchTouchEvent():
只要事件传递到了当前View,那么dispatchTouchEcent方法就一定会被调用。返回结果表示是否消费当前事件。
onInterceptTouchEvent():
在dispatchTouchEcent方法内部调用此方法,用来判断是否拦截某个事件。如果当前ViewGroup拦截了某个事件,那么在这同一个事件序列中,此方法不会再次被调用(从代码层面上解释,因为如果当前ViewGroup拦截了某个事件,那么mFirstTouchTarget == null,所以调用onInterceptTouchEvent()方法的if语句是不会执行的)。返回结果表示是否拦截当前事件。
onTouchEvent():
在dispatchTouchEvent方法内调用此方法,用来处理事件。返回true表示消费了该事件;返回false表示没有消费该事件,事件将会向上传递给父容器。
上面的解释听起来比较抽象,我们可以用一段伪代码来表示上面三个方法的关系:
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean result = false; // 默认状态为没有消费过
if (!onInterceptTouchEvent(ev)) { // 如果没有拦截,则交给子View
result = child.dispatchTouchEvent(ev);
}
if (!result) { // 如果事件没有被消费,则询问自身onTouchEvent
result = onTouchEvent(ev);
}
return result;
}
上面的伪代码很好的解释了三个方法之间的关系,我们也可以从伪代码中大致摸索到事件传递的顺序规则:
当点击事件传递到根ViewGroup里,会执行dispatchTouchEvent,在其内部会先调用onInterceptTouchEvent询问是否拦截事件,若拦截,则执行onTouchEvent方法处理这个事件;若不拦截,则执行子元素的dispatchTouchEvent,进入向下分发的传递,直到事件被处理。
在处理一个事件的时候,是有优先级的,如果设置了OnTouchListener,会先执行其内部的onTouch()方法,这时若onTouch()方法返回true,那么表示事件被处理了,不会向下传递了;如果返回了false,那么事件会继续传递给onTouchEvent()方法处理,在onTouchEvent()方法中判断如果设置了OnClickListener,那么就会调用其onClick()方法。
所以其优先级为:OnTouchListener>onTouchEvent>OnClickListener。
《Android开发艺术探索》这本书里总结了11条关于事件传递的结论:
1.同一个事件序列是指手机接触屏幕那一刻起,到离开屏幕那一刻结束,由一个down事件,若干个move事件,一个up事件构成。
2.某个View一旦决定拦截事件,那么这个事件序列之后的事件都会由它来处理,并且不会再调用onInterceptTouchEvent()。
3.正常情况下,一个事件序列只能被一个View拦截并消耗。这个原因可以参考第2条,因为一旦拦截了某个事件,那么这个事件序列里的其他事件都会交给这个View来处理,所以同一事件序列中的事件不能分别由两个View同时处理,但是我们可以通过特殊手段做到,比如一个View将本该自己处理的事件通过onTouchEvent强行传递给其他View处理。
(2和3没有考虑到子View调用requestDisallowInterceptTouchEvent()的情况,子View在获取到Down事件的情况下是可以通过requestDisallowInterceptTouchEvent()来让父View拦截事件的)
4.一个View如果开始处理事件,如果它不处理down事件(onTouchEvent里面返回了false),那么这个事件序列的其他事件就不会交给它来继续处理了,而是会交给它的父元素去处理。
5.如果一个View处理了down事件,却没有处理其他事件,那么这些事件不会交给父元素处理,并且这个View还能继续收到后续的事件。而这些未处理的事件,最终会交给Activity来处理。
即如果View只消耗down事件,而不消耗其他事件,那么其他事件不会回传给父ViewGroup,而是最终交给Activity的onTouchEvent()方法。看下Activity的dispatchTouchEvent()方法就清晰了:
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); } ```
6.ViewGroup的onInterceptToucheEvent默认返回false,也就是默认不拦截事件。
7.View没有InterceptTouchEvent方法,如果有事件传过来,就会直接调用onTouchEvent方法。
8.View的onTouchEvent方法默认都会消耗事件,也就是默认返回true,除非他是不可点击的(longClickable和clickable同时为false)。
9.View的enable属性不会影响onTouchEvent的默认返回值。就算一个View是不可见的,只要他是可点击的(clickable或者longClickable有一个为true),它的onTouchEvent默认返回值也是true。
10.onClick方法会执行的前提是当前View是可点击的,并且它收到了down和up事件。
11.事件传递过程是由外向内的,也就是事件会先传给父元素在向下传递给子元素。但是子元素可以通过requestDisallowInterceptTouchEvent来干预父元素的分发过程,但是down事件除外(因为down事件方法里,会清除所有的标志位)。
事件冲突
一个事件只能被一个View所消费,如果消费事件的View不是我们期待的View,则称为产生了事件冲突。
MotionEvent
View继承关系
ViewGroup,先要走分发事件流程,再走处理事件流程
View,只能走处理事件流程
onTouch与onClick之间会产生事件冲突吗?
看下View的dispatchTouchEvent()方法:
//View.java
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent 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;
}
...
}
View的dispatchTouchEvent方法先执行mOnTouchListener的onTouch()方法,只有onTouch()方法返回false时,才去执行onTouchEvent()方法,onClick()方法是在onTouchEvent()方法中调用的。
所以只要onTouch()方法返回true,则onClick()方法是不会执行的。
ViewGroup的事件分发(ViewGroup的dispatchTouchEvent()源码分析)
//ViewGroup.java
@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();
}
/** 步骤1:检查是否要拦截事件。
两种情况会判断是否要拦截事件:
1).如果是ACTION_DOWN事件。
2).如果DOWN事件已经有子View消费了(mFirstTouchTarget != null),那么后续来的MOVE事件也会判断是否要拦截。
*/
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {//如果是ACTION_DOWN事件或者已经有targets要消费该事件,则进行判断是否要拦截事件。
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {//只有disallowIntercept为false,才会调用onInterceptTouchEvent()判断是否拦截
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else { // 如果不是ACTION_DOWN事件,并且也没有targets要消费该事件,则ViewGroup进行拦截,自己处理该事件
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// 如果要拦截该事件,则下面的步骤2是不会执行的,直接执行步骤3进行事件分发
// 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;
//步骤2:如果不拦截事件,则进行寻找targets来消费该事件
if (!canceled && !intercepted) {//如果不拦截,
// If the event is targeting accessibility 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;
//只有对DOWN事件才会分发,MOVE和UP事件不会分发
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;//ViewGroup的直接子View的数量
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();//对直接子View按照Z轴进行排序
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;
}
//判断这个child是否能接收事件,并且点击事件是否在child范围里面
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//走到这里,说明这个child能接收事件,并且点击事件在child范围里面
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);
//调用dispatchTransformedTouchEvent()方法将事件分发给child,dispatchTransformedTouchEvent()返回true表示child处理了该事件
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// 进入到这里表示child处理了该事件
// 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();
//调用addTouchTarget()为该child创建一个新的TouchTarget插入到mFirstTouchTarget指向的链表的前面(头插法)
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;
}
}
}
//步骤3:事件分发流程(normal event dispatch),进行事件的分发和处理。拦截或者不拦截事件都会走到这里
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
/**
步骤3.1:
对于DOWN事件两种情况会走到这里:
1).如果自己不拦截DOWN事件但是没子View领取DOWN事件
2).如果自己拦截了DOWN事件。
对于MOVE事件三种情况会走到这里:
1).如果自己不拦截DOWN事件,但是没子View领取DOWN事件(即没子View消费DOWN事件),那么后续的MOVE事件都会走这里
2).如果自己不拦截DOWN事件,并且有子View领取DOWN事件,但是后面自己又拦截了MOVE事件,那么MOVE事件序列中的第二个MOVE事件及后续的MOVE事件会走这里
3).如果自己拦截了DOWN事件,那么后续的MOVE事件都会走这里
*/
// child参数传null,表示自己处理该事件
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
/**
步骤3.2:
对于DOWN事件:
如果自己不拦截DOWN事件,并且有子View领取DOWN事件
对于MOVE事件:
如果自己不拦截DOWN事件,并且有子View领取DOWN事件,但是后面自己又拦截了MOVE事件,那么MOVE事件序列中的第一个MOVE事件会走这里
如果自己不拦截DOWN事件,并且有子View领取DOWN事件,后面自己也没有拦截MOVE事件,那么MOVE事件都会走这里。
*/
// 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) {//while循环解决多点触控
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
//步骤3.2.1:DOWN事件分发会走这里,如果alreadyDispatchedToNewTouchTarget=true并且target == newTouchTarget表示上面child已经处理过了
handled = true;
} else {
//步骤3.2.2:MOVE事件分发会走这里
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;
}
/**
* 调用该方法的结果是:要么ViewGroup自己处理了事件,要么child递归进行上述分析的dispatchTouchEvent()流程
*
* 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);//分发一个cancel事件给child
}
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) {//如果child==null,则调用super.dispatchTouchEvent()进行处理事件,即调用View的dispatchTouchEvent()
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;
}
/**
* Adds a touch target for specified child to the beginning of the list.
* Assumes the target child is not already present.
*/
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
/**
* 判断一个View能否接收事件,满足两个条件中的一个:
* 1.View是VISIBLE的
* 2.如果View不是VISIBLE,但是有动画
*
* Returns true if a child view can receive pointer events.
* @hide
*/
private static boolean canViewReceivePointerEvents(@NonNull View child) {
return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null;
}
/**
* 判断点击事件是否在child里面
*
* Returns true if a child view contains the specified point when transformed
* into its coordinate space.
* Child must not be null.
* @hide
*/
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;
}
总结
一、
ViewGroup,先要走分发事件流程,如果没人处理事件,就再走处理事件流程
View,只能走处理事件流程
二、
分发流程:
DOWN–确定事件给谁
1.先判断是否拦截后自己处理事件(即不分发下去)
2.如果不拦截,则分发下去,主要步骤:
排序,对子View按照z轴进行排序
分发,遍历排序好的子View,判断哪个子View需要领取事件
领取事件的子View 处理事件
3.如果没子View领取或者自己要拦截该事件,再看下自己是否要处理该事件,进行事件分发处理流程
(如果自己要拦截该事件,则相当于自己是最后一个View,要判断自己是否要处理该事件)
MOVE–处理事件
1.先看是否拦截后自己处理事件(即不分发下去),子View可以请求不拦截
2.分发下去:
直接由down事件确定的子view进行事件处理
拦截MOVE事件—只能在MOVE事件中处理事件冲突
如果之前已经将事件分发给了子View,但是后来父容器拦截了MOVE事件,则
第一个MOVE事件会走步骤3.2.2:给子View发送一个cancel事件,并且将mFirstTouchTarget置为null(对于单点触摸事件mFirstTouchTarget指向的链表只有一个节点,mFirstTouchTarget = next;
的结果即将mFirstTouchTarget置为null)。这时候父容器是没有处理这个MOVE事件的。
第二个MOVE事件到来时会走步骤3.1,这时候父容器才处理事件。
三、
对于叶节点,如果没有拿到DOWN事件,则也就拿不到MOVE和UP事件;但是对于非叶节点,如果没有拿到DOWN事件,也可以拿到MOVE和UP事件。
四、
对于ACTION_MOVE和ACTION_UP事件,因为mFirstTouchTarget != null,所以也会调用onInterceptTouchEvent()判断是否要拦截:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
// 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;
}
...
}
五、
只有ACTION_DOWN事件才会从直接子View中寻找TouchTarget,寻找到新的TouchTarget时会更新mFirstTouchTarget,所以只要找到TouchTarget那么mFirstTouchTarget就!=null,如果没有从子View中找到TouchTarget或者自己拦截了事件,则TouchTarget==null。ACTION_MOVE事件不会寻找TouchTarget。
六、
当子View作为TouchTarget,但是后面的MOVE事件父容器进行了拦截,则第一个MOVE事件会转为CANCEL事件分发给TouchTarget。
七、
子View一旦拿到DOWN事件,后面的事件由谁处理是由子View决定的。
八、
父布局可以拦截子布局的事件,但是子布局不能拦截父布局的事件。
比如子布局消费掉DOWN事件后,父布局是可以把后续的MOVE事件拦截下来自己处理的(子布局调用getParent().requestDisallowInterceptTouchEvent(false);后父布局就可以拦截MOVE事件了),但是MOVE事件一旦被父布局拦截下来,则再后面的MOVE事件和UP事件再也不会分发到子布局了。
View的事件分发(View的dispatchTouchEvent()源码分析)
//View.java
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
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;
}
//步骤1:先调用mOnTouchListener的onTouch()方法判断是否消消费事件
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//步骤2:然后再调用View#onTouchEvent()方法判断是否消消费事件
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;
}
/**
* Implement this method to handle touch screen motion events.
* <p>
* If this method is used to detect click actions, it is recommended that
* the actions be performed by implementing and calling
* {@link #performClick()}. This will ensure consistent system behavior,
* including:
* <ul>
* <li>obeying click sound preferences
* <li>dispatching OnClickListener calls
* <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
* accessibility features are enabled
* </ul>
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return clickable;
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
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 (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
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();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
if (!clickable) {
checkForLongClick(0, x, y);
break;
}
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
checkForLongClick(0, x, y);
}
break;
case MotionEvent.ACTION_CANCEL:
if (clickable) {
setPressed(false);
}
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
break;
case MotionEvent.ACTION_MOVE:
if (clickable) {
drawableHotspotChanged(x, y);
}
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
// Remove any future long press/tap checks
removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
break;
}
return true;
}
return false;
}
滑动冲突
滑动冲突的基本形式
介绍完了事件分发机制的基本流程,我们来看看滑动冲突。滑动冲突的基本形式分为两种基本形式:
1:外部滑动方向与内部方向不一致。
2:外部方向与内部方向一致。
其他复杂的滑动冲突都可以拆成这两种基本形式。
先来看第一种,比如你用ViewPaper和Fragment搭配,而Fragment里往往是一个竖直滑动的ListView,这种情况是就会产生滑动冲突,但是由于ViewPaper本身已经处理好了滑动冲突,所以我们无需考虑,不过若是换成ScrollView,我们就得自己处理滑动冲突了。图示如下:
再看看第二种,这种情况下,因为内部和外部滑动方向一致,系统会分不清你要滑动哪个部分,所以会要么只有一层能滑动,要么两层一起滑动得很卡顿。图示如下:
对于这两种情况,我们处理的方法也很简单,并且都有相应的套路。
第一种:第一种的冲突主要是一个横向一个竖向的,所以我们只要判断滑动方向是竖向还是横向的,再让对应的View滑动即可。
判断的方法有很多,比如竖直距离与横向距离的大小比较;滑动路径与水平形成的夹角等等。
第二种:对于这种情况,比较特殊,我们没有通用的规则,得根据业务逻辑来得出相应的处理规则。举个最常见的例子,ListView下拉刷新,需要ListView自身滑动,但是当滑动到头部时需要ListView和Header一起滑动,也就是整个父容器的滑动。如果不处理好滑动冲突,就会出现各种意想不到情况。
滑动冲突的处理方法
滑动冲突的拦截方法有两种:
1.外部拦截法
一种是让事件都经过父容器的拦截处理,如果父容器需要则拦截,如果不需要则不拦截,称为外部拦截法,其伪代码如下:
在这里,首先down事件父容器必须返回false ,因为若是返回true,也就是拦截了down事件,那么后续的move和up事件就都会传递给父容器,子元素就没有机会处理事件了。
其次是up事件也返回了false,一是因为up事件对父容器没什么意义,其次是因为若事件是子元素处理的,却没有收到up事件会让子元素的onClick事件无法触发。
2.内部拦截法
另一种是父容器不拦截任何事件,将所有事件传递给子元素,如果子元素需要则消耗掉,如果不需要则通过requestDisallowInterceptTouchEvent方法交给父容器处理,称为内部拦截法,使用起来稍显麻烦。
伪代码如下:
首先我们需要重写子元素的dispatchTouchEvent方法:
然后修改父容器的onInterceptTouchEvent方法:
这里父容器也不能拦截down事件。