一、点击事件的传递规则
1、事件分发过程
//伪代码
fun dispatchTouchEvent(event: MotionEvent?) : Boolean{
var consume = false
if (onInterceptTouchEvent(event)) {
consume = onTouchEvent(event)
} else {
consume = child.dispatchTouchEvent(event)
}
return consume
}
dispatchTouchEvent
用来进行事件的分发,如果事件能传递给当前View,那么此方法一定会被调用,返回结果受当前View的onTouchEvent和下级View的dispatchEvent方法的影响,表示是否消耗当前事件。
onInterceptTouchEvent
用来判断是否拦截某个事件,如果当前View拦截了某个事件,那么在同一个时间序列当中,此方法不会被再次调用,返回结果表示是否拦截当前事件。
onTouchEvent
用来处理点击事件,返回结果表示是否消耗当前事件,如果不消耗,则在同一个事件序列中,当前View无法再次接受到事件。
2、View处理事件顺序
1、如果View设置了onTouchListener,先调用OnTouchListener.onTouch方法,如果为true则onTouchEvent 返回true。
2、如果当前设置了OnClickListener,在onTouch执行后会执行onClick,可见onClickListener的优先级最低,处于事件传递的尾端。
3、当一个点击事件产生后,它的传递过程遵循:Activity->Window->View,顶级View接收到事件后就会按照事件分发机制去分发事件。
3、总结
(1)同一个事件序列是指从手指触碰屏幕的那一刻起,到手指离开屏幕的那一刻结束,在这个过程中所产生的的一系列事件,以down事件开始,中间含有数量不定的move事件,最终以up事件结束。
(2)正常情况下一个事件序列只能被一个View拦截且消耗,因为一旦一个元素拦截了某此事件,那么同一个事件序列的所有事件都会直接交给它处理。
(3)某个View一旦决定拦截,那么这个事件序列都只能由它来处理,并且它的onInterceptTouchEvent不会再被调用。
(4)某个View一旦开始处理事件,如果它不消耗ACTION_DOWN事件,那么同一个事件序列中的其他事件都不会再交给它来处理,并且事件将重新交由它的父元素去处理,即父元素的onTouchEvent会被调用。
(5)如果View不消耗除ACTION_DOWN以外的其他事件,那么这个点击事件就会消失,此时父元素的onTouchEvent并不会被调用,并且当前View可以持续受到后续的事件,最终这些消失的点击事件会传递给Activity处理。
(6)ViewGroup默认不拦截任何事件。Android源码中ViewGroup的OnInterceptTouchEvent方法默认返回false。
(7)View没有onInterceptTouchEvent方法,一旦有点击事件传递给它,那么它的onTouchEvent方法就会调用。
(8)View的onTouchEvent默认都会消耗事件,除非它是不可点击的(clickable和longClickable都会false)。View的longClickable属性默认为false,clickable属性要分情况,如Button的clickable属性默认为true,而TextView的clickable属性默认为false。
(9)View的enable属性不影响onTouchEvent的默认返回值,哪怕一个View是disable状态的,只要它的clickable或者longClickable一个为true,那么它的onTouchEvent就返回true。
(10)onClick会发生的前提是当前View是可点击的,并且它收到了down和up的事件。
(11)事件传递是由外向内的,即事件总是先传递给父元素,然后由父元素分发给子View,通过requestDisallowInterceptTouchEvent方法可以在子元素中干预父元素的事件分发过程,ACTION_DOWN事件除外。
二、源码分析
1、Activity对点击事件的分发过程
touch事件最先传递给当前Activity,由Activity的dispatchTouchEvent来进行事件派发,具体工作由Activity内部的Window来完成,Window会将事件传递给decorView。
#Activity.java
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
#PhoneWinow.java
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
#DecorView.java
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
Window的唯一实现类是PhoneWindow。DecorView继承了FrameLayout,所以它的super.dispatchTouchEvent实际上就是调用了ViewGroup#dispatchTouchEvent。
2、顶级View对点击事件的分发过程
(1)事件拦截
先看ViewGroup.dispatchTouchEvent中部分代码,关于判断View是否拦截点击事件。
@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;
}
...
}
...
}
private void resetTouchState() {
clearTouchTargets();
resetCancelNextUpFlag(this);
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
mNestedScrollAxes = SCROLL_AXIS_NONE;
}
ViewGroup在以下两种情况下会判断是否拦截当前事件:事件类型为ACTION_DOWN或mFirstTouchTarget != null。mFirstTouchTarget指向成功处理了touchEvent的子元素,当ViewGroup不拦截事件并将事件交给子元素处理时mFirstTouchTarget != null 为true;一旦事件由当前ViewGroup拦截时,mFirstTouchTarget != null 为false。
FLAG_DISALLOW_INTERCEPT标志位,该标志位是通过requestDisallowInterceptTouchEvent设置的,一般用于子View中。该标志位一旦设置后,ViewGroup将无法拦截除了ACTION_DOWN以外的其他点击事件。因为在判断MotionEvent为ACTION_DOWN时会通过resetTouchState方法重置该标志位。
结论
当ViewGroup决定拦截事件后,那么后续的点击事件将会默认交给它处理并且不再调用它的onInterceptTouchEvent方法。FLAG_DISALLOW_INTERCEPT这个标志的作用是让ViewGroup不再拦截事件,前提是ViewGroup不拦截ACTION_DOWN事件。
(2)分发事件
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
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 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 (!child.canReceivePointerEvents()
|| !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;
}
...
}
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;
}
/**
* 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;
}
分发事件的逻辑,首先遍历ViewGroup中的所有子元素,判断子元素是否能够接收到点击事件(!child.canReceivePointerEvents() || !isTransformedTouchPointInView(x, y, child, null)),根据子元素是否在执行动画与坐标是否在子元素内且可见。
在dispatchTransformedTouchEvent方法中调用了子元素的dispatchTouchEvent方法,由子元素继续向下分发事件。如果子元素消耗了事件,则dispatchTransformedTouchEvent返回true,同时通过addTouchTarget()更新mFirstTouchTarget,跳出for循环;如果子元素的dispatchTouchEvent返回false,则ViewGroup会把事件分发给下一个子元素。
addTouchTarget中完成了对mFirstTouchTarget的赋值,mFirstTouchTarget其实是一种单链表结构。mFirstTouchTarget是否被赋值,将直接影响到ViewGroup对事件的拦截策略,如果mFirstTouchTarget为null,那么ViewGroup就默认拦截接下来同一序列所有的点击事件。
(3)特殊情况
如果遍历所有的子元素后事件没有被合适地处理,有两种可能:
1、ViewGroup没有子元素
2、子元素处理了点击事件,但是在dispatchTouchEvent中返回了false,这一般是因为子元素在onTouchEvent中返回了false。
public boolean dispatchTouchEvent(MotionEvent ev) {
...
// 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 {
...
}
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean 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;
}
在这种情况下,ViewGoup会自己处理点击事件,这时就回到了View的dispatchTouchEvent方法处理。
一开始有个疑问就是,为什么很多情况 如FrameLayout嵌套RecyclerView,当MOVE事件产生后,FrameLayout.onInterceptTouchEvent方法不调用,原因只能是RecyclerView将父容器的FLAG_DISALLOW_INTERCEPT标志值设为true
View对点击事件的处理过程
(1)dispatchTouchEvent 分发事件
/**
* 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) {
...
boolean result = false;
...
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//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;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
...
return result;
}
1、首先判断有没有设置OnTouchListener,如果onTouchListener.onTouch()返回true,则onTouchEvent方法不会调用。
2、接着判断onTouchEvent方法,如果返回true则表示消耗掉此次事件。
(2)onTouchEvent
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;
}
}
...
}
1、当View处于不可用状态下,如果此时View是可点击的,onTouchEvent仍然会消耗点击事件但不会触发点击回调。
2、在处理View本身的touch事件前,还会对View的代理mTouchDelegate做一层检测,如果为true则返回。
关于点击回调
public boolean onTouchEvent(MotionEvent event) {
...
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
...
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
...
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();
}
}
}
...
break;
...
}
return true;
}
return false;
}
public boolean performClick() {
// We still need to call this method to handle the cases where performClick() was called
// externally, instead of through performClickInternal()
notifyAutofillManagerOnClick();
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
3、只要View的CLICKABLE和LONG_CLICKABLE有一个为true,那么它就会消耗这个事件,即onTouchEvent返回true,不管它是不是disable状态。
4、当ACTION_UP发生时,会触发performClick方法,在performClick中回调点击监听。
5、View的LONG_CLICKABLE属性默认为false,而CLICKABLE的值与具体的View有关,设置了相应的事件后对应的标志值也会被置为true。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
public void setOnLongClickListener(@Nullable OnLongClickListener l) {
if (!isLongClickable()) {
setLongClickable(true);
}
getListenerInfo().mOnLongClickListener = l;
}
三、ACTION_CANCEL
ACTION_CANCEL事件是收到前驱事件后,后续事件被父控件拦截的情况下产生,onTouchEvent的事件回传到父控件只会发生在ACTION_DOWN事件中
结尾
摘抄自《Android开发艺术探索》