之前也是了解过事件分发机制,对于整个流程有个大概的印象,现在有闲余时间,正好对整个流程分析一遍算是巩固下相关知识吧。
关于时间分发机制这个东西如果你在ViewPager中放过ListView等一些上下滑动控件你就会有非常深刻的印象,上下滑动时是ListView的列表在滑动,而左右滑动的时候又是ViewPager在切换,为什么这么神奇呢?那就是因为系统帮我们处理好了这些事件分发,你的滑动手势决定哪一个控件去处理当前的事件。
那接下来就去分析分析这个神奇的机制吧~
ViewGroup事件分发:
Untitled.png当我们手指触摸到屏幕时,一个Touch事件就产生了,它的传递过程会如图所示,首先传递到当前Activity中如果当前Activity上年有Dialog或者其他的Window,那么这个事件会首先交给它们,如果不存在的话那么会调用DecorView的dispatchTouchEvent()方法去处理,如果返回false最终就会调用activity的onTouchEvent(),DecorView是PhoneWindow中的一个内部类继承于FrameLayout我们在activity中去setContentView时其实就是把我们的布局填充后又加到DecorView中
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker
那么归根究底DecorView还是一个ViewGroup,而我们通常一般又不会在activity中去处理touch事件,所以分析事件分发就可以从ViewGroup入手了,那谁谁来说过了解事情真的真相就去read the fucking source code...
我们这里分析的是5.0版本源码,其他版本的思想原理都是大致一样的
打开ViewGroup的dispatchTouchEvent()源码
ViewGroup代码模块一:
/**
* {@inheritDoc}
*/
@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;
}
// 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;
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity 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 = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(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 (!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);
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;
}
}
}
// 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;
}
这段源码非常的长我也不准备一行一行的去分析,弄清大体思路逻辑就行了,
第22行这个判断是在每次新事件序列开始时重置之前所有记录的事件状态信息。
一次事件序列就是从down事件开始到up事件结束:down事件->一系列move事件->最后up事件
在ViewGroup代码模块第22行和32行可以看到在每次一个新的事件序列开始时都会重置所有事件状态并重新执行是否拦截判断逻辑,如果在这个事件序列一开始从down事件就被拦截,那么在这个事件序列down之后的一系列事件中拦截判断逻辑都不会再执行。
如果Down事件没有被拦截,那么就会去遍历当前ViewGroup下的所有child,ViewGroup代码模块一第110行中我们看这段代码
1、
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
我们着重分析下这段代码中的canViewReceivePointerEvents(child)这个方法
2、
/**
* Returns true if a child view can receive pointer events.
* @hide
*/
private static boolean canViewReceivePointerEvents(View child) {
return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null;
}
在标题1的if判断逻辑中必须二个方法全部返回true才会不走if里面逻辑否则只要有任何一个返回了false那么就会continue去判断下一个child,标题1中的具体代码实现就在标题2中
也就是说标题2中必须child是visible可见的,或者正在执行动画或者准备执行动画,这个方法才会返回true,如果child是不可见的并且没有设置动画那么就会返回false,因为能见到这个view才可以点击嘛,都invisible或者gone掉看不见了,点击就没意义了,正在执行动画或者状态标记可见都是可见状态二者满足其一,标题1中的第二个判断方法很好理解了,当前触摸的事件位置如果在child范围内就返回true,否则返回false。
这里插入一小节细节
我们启动动画后view状态肯定是可见得了,当动画执行完毕会调用在view中draw方法里调用这个方法结束动画
if (a != null && !more) {
if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
onSetAlpha(255);
}
parent.finishAnimatingView(this, a);
}
这个方法就会调用 view.clearAnimation();
此时child.getAnimation()获取到的就为null,所以这段分析为了证明 view.clearAnimation()!=null时表示view在执行动画一定可见,所以上面代码判断二个满足其一即可
child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null;
ViewGroup代码模块二:
接下在125行代码中来会执行这个方法
dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)
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;
}
这个方法也是炒鸡长,挑重点看,第55行如果这个child为null(一般child都不会为null)直接调用super.dispatchTouchEvent(event)也就是parent调用View中的dispatchTouchEvent(event),否则调用child的dispatchTouchEvent(event),如果这个child是viewgroup的话又会重复走之前的逻辑这么一层层的递归下去, 那么最终最底层的child都是view都会走到View的dispatchTouchEvent,相应的进行View的事件分发,最终都会作为dispatchTransformedTouchEvent这个方法的返回值,如果返回了true代表消费事件序列中的Down事件 ,接着会走if下面逻辑我们看看ViewGroup代码模块一141这一行
newTouchTarget = addTouchTarget(child, idBitsToAssign);
/**
* Adds a touch target for specified child to the beginning of the list.
* Assumes the target child is not already present.
*/
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
看到没,我们上面说了走if表示child消费这次Down事件,这段代码会把消费事件的这个child赋值给我们ViewGroup代码模块一中第32行中看到的mFirstTouchTarget这个变量中。
这就是一次完整的Down事件分发过程。
我们继续看下面,ViewGroup代码模块一的第166行,如果事件在down事件中被拦截或者在ViewGroup代码模块一66行中分发的所有child都没有消费这个down事件那么mFirstTouchTarget==null的,此时就会去调用这段代码自己处理这次事件
// 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);
}
如果自己也不消费这次事件就会往上传递给parent
如果child消费了这个down事件,那么就会else中下面这段代码
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
}
alreadyDispatchedToNewTouchTarget会在child消费事件后被赋值true,
而 mFirstTouchTarget在child消费事件后也会等于newTouchTarget ,所以如果child消费了down事件这段if代码会被直接执行
也就是说当down事件被消费了,down后面一系列事件序列的move...之类的事件来临时,newTouchTarget在ViewGroup代码模块一59行被赋值为null ,这样的话就会走这里面的179行中else的dispatchTransformedTouchEvent方法去分发后面的move等一系列事件
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
好到我们总结一下上面所有分析
1、一个事件序列是从最顶层的ViewGroup开始传递的,通过ViewGroup中的dispatchTouchEvent方法分发给所有的child
2、遍历所有的child,当child不为null时,调用child的dispatchTouchEvent方法,如果child是一个ViewGroup那么重复1过程
3、当child的dispatchTouchEvent返回true时表示这个child要消费这次down事件,125行dispatchTransformedTouchEvent为true会break跳出遍历child循环,并且mFirstTouchTarget变量会被赋值给这个child
4、mFirstTouchTarget!=null时,并且是事件序列down后面一系列事件时,就会调用ViewGroup代码模块一182行去分发move。。。。等一系列事件。
5、如果情况3child的dispatchTouchEvent返回false表示不消费这次down事件的话,那么就会走ViewGroup代码模块一168行去调用自己的super.dispatchTouchEvent(event)方法也就是View中的dispatchTouchEvent自己去处理这次事件。
6、如果自己dispatchTouchEvent也返回false表示自己也不处理,那么就会层层向上抛给parent,直到顶层的DecorView也不处理就会抛给Activity,Activity默认不处理那么这个事件默认就丢掉
7、假如情况3中child消费了一个序列事件中的down事件,但是后续的move。。。等事件都不消费那么后序事件也不会向上抛给parent去处理(因为分发一个事件序列是根据down事件判断的,如果down事件被消费了,那么表示这个序列的后序所有事件都交给view自己去处理),因为down事件被消费后mFirstTouchTarget就被赋值了,在这次事件序列中都不会走ViewGroup代码模块一中166行,除非重新一个新的事件序列开始。
通过上面很长的源码分析我们已经搞懂了ViewGroup的事件分发过程,那么当ViewGroup将事件传递给最下面的child view时,view是如何处理自己的事件分发的呢?下面继续分析源码吧.
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;
}
可以看到相比ViewGroup,View的dispatchTouchEvent源码少了很多,还是老规矩挑重点开始分析,第24行如果View enable可用并且手指正在拖拽滚动条直接返回true,这段我们暂时不用管,重点看30行,如果mOnTouchListener不为null时就会调用onTouch这个方法,mOnTouchListener我们是这样设置进去的。
public void setOnTouchListener(OnTouchListener l) {
getListenerInfo().mOnTouchListener = l;
}
如果我们没设置mOnTouchListener或者mOnTouchListener中不消费Down事件的话result就还是为false,接着看36行,这个时候会调用onTouchEvent方法,这个方法是需要我们在View中重写的,我们点进去super看看View中这个方法实现
View代码模块二
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)) {
performClick();
}
}
}
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;
}
这里面代码也超级长,依旧挑重点分析,我们主要关注涉及到返回值的地方,第7~19行如果我们setEnable(false)那么clickable的值就为false,注释也解释了,如果这个View是不可用的我们任然消费这个事件,只不过不去相应,只要我们不设置setEnable(false)那么就会继续往下执行,第20看到没不知道是不是新增api,我们可以在View里设置一个代理用代理控制事件的消费,有点叼吧。
public void setTouchDelegate(TouchDelegate delegate) {
mTouchDelegate = delegate;
}
假设我们什么都没设置的话就会走到第26行,可以看到在UP事件中第63行中调用了这么一段代码
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
private final class PerformClick implements Runnable {
@Override
public void run() {
performClick();
}
}
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;
}
可以看到PerformClick是一个Runnable任务,post调用它的run方法最终会执行到最后一段代码,这里有没有看见熟悉的身影?不错就是我们最常用的setOnClickListener假设我们设置了点击事件,那么在up事件中直接调用onClikc回调方法并且返回ture,并且我们可以通过setOnClickListener内部看到只要设置了点击事件那么这个View的ViewFlag就是可点击的所以在onTouchEvent方法中一定会走到UP里执行onClick()方法。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
好我们总结一下View中dispatchTouchEvent()事件分发过程
- 首先我们清楚了View中的事件分发的优先级是: onTouch>onTouchEvent>onClick的
- 如果我们设置了setOnTouchListener的话,一开始事件序列会被优先传递到onTouch里,假如Down事件被onTouch消费了,那么就直接return true(那么onTouchEvent不会被调用,onClick事件也不会被调用),假如事件没有被消费那么接着会调用View中的onTouchEvent方法,当View可点击时onTouchEvent方法会接收到事件序列,View中的onTouchEvent接收事件后默认是全部都返回true的也就是默认是消费所有事件,这点在View代码模块二的第159行可以看到。
- onClick事件是在View中的onTouchEvent里的UP事件内执行的,这点在上面代码中就可以看到,从这我们可以发现假如我们在View中重写了onTouchEvent方法并且在down事件中返回了false不消费down事件的话,那么我们的设置的click事件也不会被响应。
Android的事件分发过程已经全部分析完毕,过程中如果不对的地方欢迎大佬指正~
网友评论