综述
Android事件的分发从Activity的dispatchTouchEvent开始一路追进入如下:
事件传递分析:
1、从TestActivity的dispatchTouchEvent开始,如果调用super.dispatchTouchEvent(ev),则事件继续向下传递,如果直接返回true或者false,则事件消费掉不再向下传递。
2、TestActivity的dispatchTouchEvent调用super.dispatchTouchEvent(ev)则会进入到Activity的dispatchTouchEvent方法中,代码如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
//此处检验为按下事件,按下事件为事件的开始
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//此方法为空方法 在activity在分发各种事件的时候会调用该方法
onUserInteraction();
}
//核心在此处
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
核心就在于getWindow().superDispatchTouchEvent(ev),如果此处返回true,则不会调用Activity的onTouchEvent,反之,则代表内部没有消费事件,则传到Activity的onTouchEvent方法中。
3、getWindow()获取到的Window对象实际为PhoneWindow对象,调用到PhoneWindow对象的superDispatchTouchEvent方法,代码如下:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
//直接调用DecorView的方法
return mDecor.superDispatchTouchEvent(event);
}
此处实际直接调用了DecorView的superDispatchTouchEvent方法,进入DecorView的superDispatchTouchEvent方法,代码如下:
public boolean superDispatchTouchEvent(MotionEvent event) {
//直接调用super方法
return super.dispatchTouchEvent(event);
}
DecorView继承自FrameLayout,super实际调用到了ViewGroup的dispatchTouchEvent方法。
到此事件传递到了ViewGroup,后面开始了正式的事件分发流程
ViewGroup的事件分发
综述:ViewGroup的事件分发实际上主要做了三件事情:
- 判断事件是否需要拦截(注释1)
- 找到分发的View(真正交互的View)(注释2)
- 分发事件到View上(注释3)
代码如下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
省略部分代码
...
boolean handled = false;
//安全校验 安全策略 不在顶部或被遮挡不响应 不符合安全策略方法直接返回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) {//mFirstTouchTarget != null 当前已经存在处理事件的子View
//判断是否允许拦截事件
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//允许拦截则调用onInterceptTouchEvent方法 [注释1,后续分析]
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
//不是按下事件并且当前不存在处理事件的子View 则事件直接拦截
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
...
省略部分代码
...
//没有取消也没有拦截 则去找真实交互的View
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;
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;
//遍历获取目标的View
for (int i = childrenCount - 1; i >= 0; i--) {
//获取下标
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
//获取View
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;
}
//检测目标View是否是处理事件的View 触摸点是否在View的范围之内
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);
//此处进行事件的分发 方法dispatchTransformedTouchEvent [注释2]
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;
}
}
}
//分发事件到具体的目标View [注释3]
// 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;
}
注释1:onInterceptTouchEvent
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则不进行拦截
注释2:dispatchTransformedTouchEvent 进行事件的分发 返回true则说明已经找到了消费事件的子View
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;
}
注释3 此处进行事件的具体分发,如果有目标View子View则进行相关的分发,
否则则调用dispatchTransformedTouchEvent传入的child为null,
在注释2中会调用到 super.dispatchTouchEvent(event),此时调用了View的 super.dispatchTouchEvent(event),进行相关事件的处理
View的事件分发
综述:View的dispatchTouchEvent操作比ViewGroup简单了许多,主要就是相关的监听器处理【注释1】及onTouchEvent处理逻辑【注释2】
源码如下:
public boolean dispatchTouchEvent(MotionEvent event) {
...
省略部分验证相关代码
...
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;
}
//listener相关验证 如果设置了监听器相关 则事件在此处消费 直接在监听器中处理 [注释1]
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//如果result仍然为false 则表示无监听相关处理 进入onTouchEvent相关的逻辑处理 [注释2]
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;
}
最后在View的onTouchEvent进行相关的事件处理。
总结:
1)事件的默认传递流程如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyView:dispatchTouchEvent -> MyView:onTouchEvent ->MyViewGroup:onTouchEvent ->
TestActivity:onTouchEvent
2) 同一个事件序列,如果子View(ViewGroup)没有处理该事件(没有消费事件),
那么后续事件就不会传递到子View中
TestActivity:dispatchTouchEvent -> TestActivity:onTouchEvent
3)如果MyView的onTouchEvent返回了true 消费了事件 则传递如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyView:dispatchTouchEvent -> MyView:onTouchEvent
4)如果MyViewGroup的onInterceptTouchEvent 返回为true,MyViewGroup的onTouchEvent返回为false,未消费事件 则事件的传递流程如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyViewGroup:onTouchEvent -> TestActivity:onTouchEvent
5)如果MyViewGroup的onInterceptTouchEvent 返回为true,MyViewGroup的onTouchEvent返回为true,消费了费事件 则事件的传递流程如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyViewGroup:onTouchEvent