一、基础认识
Android 中事件的传递流程:
Activity--------> Window(PhoneWindow)------>DecroView------->ViewGroup----->View;
二、Activity中事件分发
屏幕发生触摸事Android系统层接受到事件,然后反馈给此时栈顶的App的Acivity,并回调Activity中的dispatchTouchEvent(MotionEvent ev)函数,然后才是事件分发与消费;在Activity中事件分发代码十分简单,源码入手:
Activity中dispatchTouchEvent(MotionEvent ev)源码:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
根据源码先向Windows传递事件,如果Window的superDispatchTouchEvent(MotionEvent ev)如果返回true[消费事件],则函数立即返回,否则继续调用Activity的onTouchEvent(MotionEvent ev)处理;
public boolean onTouchEvent(MotionEvent event) {
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
- 在Activity中可以直接是重新onTouchEvent函数实现拦截事件,需要注意的是根据dispatchTouchEvent中源码可知,如果需要在保证在Activiy的其他组件中不能拦截事件,否则Activity中dispatchTouchEvent函数就无效了。
三、 Window、DecorView中事件分发
PhonWindow中superDispatchTouchEvent(MotionEvent ev)源码;
根据Activity中的 dispatchTouchEvent(MotionEvent ev) 源码可知继续向Window传递事件的,在Android中Window是一个抽象类并且只有PhoneWindow一个子类,所以直接看PhonWindow中的superDispatchTouchEvent(MotionEvent ev);
public boolean superDispatchTouchEvent(MotionEvent event) {
return this.mDecor.superDispatchTouchEvent(event);
}
显然在PhoneWindow中是直接传递给DecorView中superDispatchTouchEvent(MotionEvent event)进行了进一步的分发的;继续跟踪DecorView中的源码:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
四、 ViewGroup中事件分发
在源码分析之前写理一下流程,然后在根据源码分段解析:
ViewGroup中事件分发函数dispatchTouchEvent(MotionEvent ev)的流程伪代码:
public boolean dispatchTouchEvent(MotionEvent ev) {
/* 事件连续性、页面焦距的 安全性 check 过滤无效事件、清楚无效数据恢复状态*/
.......
/*是否拦截、取消的判断*/
if (actionMasked != 0 && this.mFirstTouchTarget == null) {
intercepted = true;
} else {
canceled = (this.mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!canceled)
intercepted = this.onInterceptTouchEvent(ev);//拦截调用onInterceptTouchEvent函数
}
/*如果当前事件没有被拦截取消,则继续向下分发*/
if (!canceled && !intercepted) {
/*准备所以是childView,并且过滤出具体需要分发的childView,*/
.......
//向下分发的目标ChildView
ArrayList<View> preorderedList = this.buildTouchDispatchChildList();
.......
/*进行向childView分发事件*/
for(int i = childrenCount - 1; i >= 0; --i) {
/*对childView进行check是否可以接受事件、分发事件之前reset状态,防止出现事件混乱【down、move、cancel……先后顺序混乱】*/
.......
/*进行向下childView分发 ,dispatchTransformedTouchEvent具体分发函数*/
if (this.dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
/*记录消费事件的目标ChildVewi的时间和在List<ChildVewi>位置*/
.......
/*记录消费事件View的对象和指针*/
newTouchTarget = this.addTouchTarget(child, idBitsToAssign);
break;
}
/*如果在childView的List中没有目标View【在触摸点击的位置没字View控件,只有Layout】*/
if (this.mFirstTouchTarget == null) {
/* 调用ViewGroup的super.dispatchTouchEvent(event),就是调用ViewGroup的父类View的dispatchTouchEvent函数,
在View的dispatchTouchEvent然后回调onTouchEvent(event) */
handled = this.dispatchTransformedTouchEvent(ev, canceled, (View)null, -1);
} else {
/*变量、对象的回收处理*/
.......
}
}}
return handled;
}
在上面的伪代码中已经把ViewGroup中的事件分发流程基本搞清楚,主要分为:
1.判断是否拦截;
2.向ChildView分发事件;
ViewGroup中dispatchTouchEvent完整源码:
public boolean dispatchTouchEvent(MotionEvent ev) {
//验证事件是否连续
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
//这个变量用于记录事件是否被处理完
boolean handled = false;
//过滤掉一些不合法的事件:当前的View的窗口被遮挡了。
if (onFilterTouchEventForSecurity(ev)) {
//如果事件发生的View在的窗口,没有被遮挡
final int action = ev.getAction();
//重置前面为0 ,只留下后八位,用于判断相等时候,可以提高性能。
final int actionMasked = action & MotionEvent.ACTION_MASK;
//判断是不是Down事件,如果是的话,就要做初始化操作
if (actionMasked == MotionEvent.ACTION_DOWN) {
//如果是down事件,就要清空掉之前的状态,比如,重置手势判断什么的。
//比如,之前正在判断是不是一个单点的滑动,但是第二个down来了,就表示,不可能是单点的滑动,要重新开始判断触摸的手势
//清空掉mFirstTouchTarget
// 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();
}
//检查是否拦截事件
final boolean intercepted;
//如果当前是Down事件,或者已经有处理Touch事件的目标了
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//判断允不允许这个View拦截
//使用与运算作为判断,可以让我们在flag中,存储好几个标志
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
//如果说允许拦截事件
if (!disallowIntercept) {
//确定是不是拦截了
intercepted = onInterceptTouchEvent(ev);
//重新恢复Action,以免action在上面的步骤被人为地改变了
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.
//如果说,事件已经初始化过了,并且没有子View被分配处理,那么就说明,这个ViewGroup已经拦截了这个事件
intercepted = true;
}
// Check for cancelation.
//如果viewFlag被设置了PFLAG_CANCEL_NEXT_UP_EVENT ,那么就表示,下一步应该是Cancel事件
//或者如果当前的Action为取消,那么当前事件应该就是取消了。
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
//如果需要(不是取消,也没有被拦截)的话,那么在触摸down事件的时候更新触摸目标列表
//split代表,当前的ViewGroup是不是支持分割MotionEvent到不同的View当中
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
//新的触摸对象,
TouchTarget newTouchTarget = null;
//是否把事件分配给了新的触摸
boolean alreadyDispatchedToNewTouchTarget = false;
//事件不是取消事件,也没有拦截那么就要判断
if (!canceled && !intercepted) {
//如果是个全新的Down事件
//或者是有新的触摸点
//或者是光标来回移动事件(不太明白什么时候发生)
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
//这个事件的索引,也就是第几个事件,如果是down事件就是0
final int actionIndex = ev.getActionIndex(); // always 0 for down
//获取分配的ID的bit数量
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;
//如果新的触摸对象为null(这个不是铁定的吗)并且当前ViewGroup有子元素
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 View[] children = mChildren;
//是否使用自定义的顺序来添加控件
final boolean customOrder = isChildrenDrawingOrderEnabled();
for (int i = childrenCount - 1; i >= 0; i--) {
//如果是用了自定义的顺序来添加控件,那么绘制的View的顺序和mChildren的顺序是不一样的
//所以要根据getChildDrawingOrder取出真正的绘制的View
//自定义的绘制,可能第一个会画到第三个,和第四个,第二个画到第一个,这样里面的内容和Children是不一样的
final int childIndex = customOrder ?
getChildDrawingOrder(childrenCount, i) : i;
final View child = children[childIndex];
//如果child不可以接收这个触摸的事件,或者触摸事件发生的位置不在这个View的范围内
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
//获取新的触摸对象,如果当前的子View在之前的触摸目标的列表当中就返回touchTarget
//子View不在之前的触摸目标列表那么就返回null
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.
//如果新的触摸目标对象不为空,那么就把这个触摸的ID赋予它,这样子,
//这个触摸的目标对象的id就含有了好几个pointer的ID了
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
//如果子View不在之前的触摸目标列表中,先重置childView的标志,去除掉CACEL的标志
resetCancelNextUpFlag(child);
//调用子View的dispatchTouchEvent,并且把pointer的id 赋予进去
//如果说,子View接收并且处理了这个事件,那么就更新上一次触摸事件的信息,
//并且为创建一个新的触摸目标对象,并且绑定这个子View和Pointer的ID
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
mLastTouchDownIndex = childIndex;
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
//如果newTouchTarget为null,就代表,这个事件没有找到子View去处理它,
//那么,如果之前已经有了触摸对象(比如,我点了一张图,另一个手指在外面图的外面点下去)
//那么就把这个之前那个触摸目标定为第一个触摸对象,并且把这个触摸(pointer)分配给最近添加的触摸目标
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.
//child view没有消费触摸事件
if (mFirstTouchTarget == null) {
// No tuch targets so treat this as an ordinary view.
// child view没有消费事件,把自己当做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;
//遍历TouchTargt树.分发事件,如果我们已经分发给了新的TouchTarget那么我们就不再分发给newTouchTarget
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
//是否让child取消处理事件,如果为true,就会分发给child一个ACTION_CANCEL事件
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
//派发事件
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
//cancelChild也就是说,派发给了当前child一个ACTION_CANCEL事件,
//那么就移除这个child
if (cancelChild) {
//没有父节点,也就是当前是第一个TouchTarget
//那么就把头去掉
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
//把下一个赋予父节点的上一个,这样当前节点就被丢弃了
predecessor.next = next;
}
//回收内存
target.recycle();
//把下一个赋予现在
target = next;
//下面的两行不执行了,因为我们已经做了链表的操作了。
//主要是我们不能执行predecessor=target,因为删除本节点的话,父节点还是父节点
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) {
//如果是多点触摸下的手指抬起事件,就要根据idBit从TouchTarget中移除掉对应的Pointer(触摸点)
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中的dispatchTransformedTouchEvent完整源码
dispatchTransformedTouchEvent的主要功能是调用childView的dispatchTouchEvent方法完成一轮的事件分发机制,如果dispatchTouchEvent返回true则表示子View消费了事件,false表示子类没有消费事件,继续事件分发;
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel, View child, int desiredPointerIdBits) {
int oldAction = event.getAction();
boolean handled;
if (!cancel && oldAction !=MotionEvent.ACTION_CANCEL) {
int oldPointerIdBits = event.getPointerIdBits();
int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
if (newPointerIdBits == 0) {
return false;
} else {
MotionEvent transformedEvent;
float offsetX;
float offsetY;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
//child为null时即没有子View时直接调用父类View的dispatchTouchEvent()把自己当做view来消费 ;
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
offsetX = (float)(this.mScrollX - child.mLeft);
offsetY = (float)(this.mScrollY - child.mTop);
event.offsetLocation(offsetX, offsetY);
//子View不为空继续调用dispatchTouchEvent向下分发;
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// newPointerIdBits != oldPointerIdBits时
if (child == null) {
//child为null时即没有子View时直接调用父类View的dispatchTouchEvent()把自己当做view来消费 ;
handled = super.dispatchTouchEvent(transformedEvent);
} else {
offsetX = (float)(this.mScrollX - child.mLeft);
offsetY = (float)(this.mScrollY - child.mTop);
transformedEvent.offsetLocation(offsetX, offsetY);
if (!child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
// 子View不为空继续调用dispatchTouchEvent向下分发;
handled = child.dispatchTouchEvent(transformedEvent);
}
transformedEvent.recycle();
return handled;
}
} else {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
//child为null时即没有子View时直接调用父类View的dispatchTouchEvent()把自己当做view来消费 ;
handled = super.dispatchTouchEvent(event);
} else {
//子View不为空继续调用dispatchTouchEvent向下分发;
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
}
ViewGroup中的addTouchTarget完整源码
private ViewGroup.TouchTarget addTouchTarget(View child, int pointerIdBits) {
ViewGroup.TouchTarget target = ViewGroup.TouchTarget.obtain(child, pointerIdBits);
target.next = this.mFirstTouchTarget;
this.mFirstTouchTarget = target;
return target;
}
ViewGroup中的requestDisallowInterceptTouchEvent完整源码
用于设置ViewGroup拦截flage
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept != ((this.mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
if (disallowIntercept) {
//重点:就是在这里给mGroupFlags添加FLAG_DISALLOW_INTERCEPT不允许拦截事件标记位
this.mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
} else {
this.mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
if (this.mParent != null) {
this.mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
}
五、 View中事件分发View中的事件分发机制
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;
}
//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);
}
// 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;
}
public boolean performClick() {
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;
}
https://blog.csdn.net/carson_ho/article/details/54136311
[1]: https://blog.csdn.net/qi1017269990/article/details/79111677