android的事件分发首先是由ViewRootImpl.java的setview开始。
1.ViewRootImpl.java setView
2.mInputEventReceiver = new WindowInputEventReceiver(inputChannel,Looper.myLooper());
3.enqueueInputEvent->doProcessInputEvents->deliverInputEvent->stage.deliver(q)
stage是InputStage,用来处理输入事件的,传递事件等,是个抽象类
4.因为inputStage是抽象类,所以接下来看具体实现ViewPostImeInputStage.java processPointerEvent方法
5.boolean handled = mView.dispatchPointerEvent(event); mView相当于DecorView,所以在DecorView里面找DispatchPointerEvent找不到,那就找超类转到dispatchTouchEvent
6.DecorView.java @Override
public boolean dispatchTouchEvent(MotionEvent ev) {
final Window.Callback cb = mWindow.getCallback();
return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
}
cb相当于activity
7.Activity.java dispatchTouchEvent->getWindow().superDispatchTouchEvent(ev)
8.PhoneWindow.java superDispatchTouchEvent->mDecor.superDispatchTouchEvent(event);->ViewGroup.java dispatchTouchEvent->dispatchTransformedTouchEvent
9.View.java的dispatchTouchEvent->
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
执行ontouchlistener方法如果返回为true则没有ontouchevent方法,也就没有onclick事件因为onclick事件是ontouchevent事件里面的ACTION_UP的performClickInternal处理的
总结
View.dispatchTouchEvent 只有事件的处理逻辑
ViewGroup.dispatchTouchEvent 实现了分发流程的逻辑
疑问
1.按下移出View,为什么 onClick 不执行
答:!pointInView(x, y, touchSlop)里面有个setPressed为false,然后在action_up的时候触发不了performClickInternal
dispatchTouchEvent方法源码解析
@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.
//当事件为action_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;
//当事件为action_down或者mFirstTouchTarget!=null//mFirstTouchTarget是个链表,保存着点击事件的信息
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//因为在其他地方可能调用了requestDisallowInterceptTouchEvent(boolean disallowIntercept)
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 {
//当不是ACTION_DOWN事件并且mFirstTouchTarget为null(即没有可以处理触摸事件的子组件)时
//设置 intercepted = true表示ViewGroup拦截触摸事件。
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// 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 isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
&& !isMouseEvent;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
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;
//如果事件为ACTION_DOWN,或者多指操作等,开启了一个循环,循环所有的子View判断哪个子View可以处理触摸事件
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 =
isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
final float y =
isMouseEvent ? ev.getYCursorPosition() : 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;
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;
}
// 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;
}
}
}
// 我们通过上面的dispatchTransformedTouchEvent可能找到一个可以处理子事件的子view
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
//如果没有找到,则调用dispatchTransformedTouchEvent()方法,就会判断ViewGroup自身是否可以处理触摸事件。
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
//如果找到了,则调用 dispatchTransformedTouchEvent()方法,
//并传值是mFirstTouchTarget,dispatchTransformedTouchEvent内部会调用子View的dispatchTouchEvent()方法,完成事件的分发,
//因为我们在上面已经找到一个可以出发触摸事件的子View,可能已经调用过dispatchTransformedTouchEvent()方法分发过一次了,所以提供了一个boolean值 //alreadyDispatchedToNewTouchTarget,避免进行重复分发。
// 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;
}
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) {
//如果子child没有就传给super.dispatchTouchEvent(event)
handled = super.dispatchTouchEvent(event);
} else {
//子child的dispatchTouchEvent方法
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;
}
1.首先是从acton_down开始,清除了上一次的点击事件的混存
2.如果是 ACTION_DOWN事件 或者 mFirstTouchTarget 不是空的,需要调用onInterceptTouchEvent()方法判断是拦截 该触摸事件。
3.如果不拦截,并且是 ACTION_DOWN事件,事件触摸的开始,首先循环所有子View,对其调用dispatchTouchEvent()方法。这时候触摸事件已经分发到了子view。这时候有个局部变量来管理,该步骤只会在ACTION_DOWN事件的时候调用一次,也就是一个触摸事件系列只会找到一个可以处理的子View。这也是为什么dispatchTouchEvent()方法返回了true,那么事件序列后续的事件都会交给一个组件处理,因为dispatchTouchEvent()方法只会在ACTION_DOWN事件的时候去寻找一个可以处理触摸事件的子View,其他事件不会去寻找。这里面主要是有个dispatchTransformedTouchEvent方法,那么后续的触摸事件ACTION_MOVE、ACTION_UP都会再次调用 这个子View的dispatchTouchEvent()方法,这就完成了 后续触摸事件分发给子view。
如果我们经过第三步,没有找到可以处理触摸事件的子View ,我们肯定是判断ViewGroup自身可不可以处理触摸事件,因为ViewGroup继承自View,所以调用了View基类的dispatchTouchEvent()方法判断ViewGroup自身可不可以处理触摸事件。
其他具体的看代码
处理事件冲突,可以在父viewgroup里处理也可以在子控件里处理,主要涉及到requestDisallowInterceptTouchEvent(boolean disallowIntercept)方法拦截