前言
上节我们已经说到事件最终传递给了DecorView
,而DecorView
是View
的子类,到了这里,而这也到了我们最关心的部分,View
及ViewGroup
是怎么对事件进行处理的,接下来我将继续讲解这部分知识。
简述
在View
和ViewGroup
中和事件分发相关的方法为dispatchTouchEvent
,onInterceptTouchEvent
和onTouchEvent
,下面我先简单的描述下着三个方法:
-
dispatchTouchEvent
:用于传递和分发事件,一般不重写此方法,其返回值由当前View和其子View决定. -
onInterceptTouchEvent
:在dispatchTouchEvent
被调用,用于判断该ViewGroup
是拦截当前事件或继续传递,在同一事件序列(即ACTION_DOWN至ACTION_UP)中,该方法不应该不重复调用, -
onTouchEvent
:此方法用于处理事件,返回值为true时则处理此事件,否则返回false.
事件传递方式
当事件传递到dispatchTouchEvent
的时候,先调用onInterceptTouchEvent
判断是否消费该事件,如果消费该事件,本事件序列将不再传递给子View
,而是传递给当前View
的onTouchEvent
方法,如果判断不消费该事件,则将事件继续往下传递,若子View
不处理该事件,子View
的传递方式依此类推,若最后一个View
仍不处理该事件,事件将逐级返回,最后传递给Activity
.
源码分析
首先我们先看下dispatchTouchEvent
中的代码(由于代码量较大,这里将使用代码片段的方式):
// 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();
}
在上面的代码中,我们可以看出,当Event
的Action
为ACTION—DOWN
的时候,会重置状态,接受新的事件序列;
// 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;
}
接着,在这里,我们看到当调用了onInterceptTouchEvent
方法,接下来我们追踪到onInterceptTouchEvent
中去看下.
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}
在这里,我们可以看到,此方法直接返回了false,也就是说,ViewGroup
默认是不拦截事件的,这中设计我们也应该明白,因为ViewGroup
是父级控件,如果拦截了事件的话,事件将如法继续往子控件分发(LinearLayout
和RelativeLayout
中也没有重写该方法,则可以体现这一思想),如果我们在自定义View
的时候需要处理是否拦截事件的时候,可以重写该方法,去判断是否拦截.接着,回到dispatchTouchEvent
,我们继续追踪:
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();
}
在这里,我们可以看到,遍历了下级View,然后判断子View
是否能接收点击事件,然后调用dispatchTransformedTouchEvent
方法.接着我们去查看下dispatchTransformedTouchEvent
中的实现:
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);
}
在这里我们看到,这里将事件传递给了子View
,接着,我们回到dispatchTouchEvent
方法中:
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;
}
在这里,我们可以看到,当子View
愿意接收事件时,则跳出循环,等等,难道不需要做点别的吗?当然是有的,在这里,会调用addTouchTarget
接下来,我们看下addTouchTarget
方法:
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
在这里,将取出来出来的TouchTarget
赋给了mFirstTouchTarget
,并返回,赋值给newTouchTarget
,接着,我们回到dispatchTouchEvent
的方法中:
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;
}
在这里,我们看到,当newTouchTarget
为null,也就是没有子View去接收事件的时候,会将事件派发给最近一次目标.接着:
// 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);
}
如上代码所示,如果没有接收的目标View
的时候,则会继续调用dispatchTransformedTouchEvent
方法,而且View传了一个null值,而根据dispatchTransformedTouchEvent
的逻辑,在View为null的时候,则会调用super.dispatchTouchEvent
即View的dispatchTouchEvent
方法,接下来,我们就去看下
View
中dispatchTouchEvent
的源码:
//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;
}
在这里我们可以看出,这里会先判断是否有mOnTouchListener
,如果与的话,则先将事件交给mOnTouchListener
去处理,若OnTouchListener
不愿意消费该事件,或者没有OnTouchListener
时,则将事件传递给onTouchEvent
,接着我们继续追踪onTouchEvent
中的实现:
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
从上面的代码可以看出,当View
的状态为DISABLED
状态时,也是会消费事件的,只是没有什么效果,在这里不是我们关注的重点,接下来我们继续往下看:
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
如上代码所示,如果View
设置了代理,事件将传递给代理,将会调用代理的onTouchEvent
如果代理选择消费事件,则返回true,我们接着看:
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
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:
mHasPerformedLongPress = false;
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);
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
从上面的代码可以看出,只要View
的CLICKABLE
,LONG_CLICKABLE
,CONTEXT_CLICKABLE
有一个为true的时候,就消费该事件,接下来我们对看下具体实现:
ACTION_DOWN:
我们可以看到,在这里调用了performButtonActionOnTouchDown
,这个方法是对鼠标点击事件的处理,在这里我们先不去关注它,接着:
-
mPrivateFlags |= PFLAG_PREPRESSED
给mPrivateFlags添加一个PFLAG_PREPRESSED
的flag; -
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout())
检测Tap事件,ViewConfiguration.getTapTimeout()
获取的值为100,到达延时时间后执行; - 我们看一下
CheckForTap
中的实现:
private final class CheckForTap implements Runnable {
public float x;
public float y;
@Override
public void run() {
mPrivateFlags &= ~PFLAG_PREPRESSED;
setPressed(true, x, y);
checkForLongClick(ViewConfiguration.getTapTimeout());
}
}
这里取消了mPrivateFlags
的PFLAG_PREPRESSED
的设置,然后设置setPressed
为true,更新点击状态,以便执行动画等,在checkForLongClick
方法中,如果View
支持长按,则检测是否为长按事件;
- 如果
View
不在一个可滑动的ViewGroup
中,则直接setPressed
,在setPressed
中会为mPrivateFlags
设置一个PFLAG_PRESSED
,然后执行checkForLongClick
.
ACTION_MOVE:
- 如果手指移动到
View
外部,就执行removeTapCallback
方法:
private void removeTapCallback() {
if (mPendingCheckForTap != null) {
mPrivateFlags &= ~PFLAG_PREPRESSED;
removeCallbacks(mPendingCheckForTap);
}
}
这里将mPrivateFlags
中的PFLAG_PREPRESSED
移除,并将Tap事件的检测取消掉;
- 如果
mPrivateFlags
重包含PFLAG_PRESSED
,也就是说如果View
是在不可滑动的父控件中时,则执行removeLongPressCallback
方法,移除长按检测,并setPressed(false)
,设置新的pressed状态.
ACTION_UP:
- 判断
mPrivateFlags
是否包含PFLAG_PREPRESSED
,当PFLAG_PREPRESSED
包含``或者PFLAG_PRESSED
时,都可以进入逻辑内部; - 如果在
prepressed
为true,也就是Tap事件检测还有执行时,手指抬起,则执行setPressed
去更新pressed
状态为True; - 接着,如果还没有执行长按事件检测,则移除长按检测;
- 继续,如果
mPerformClick
为null的话,则创建一个mPerformClick
,然后post到队列中,如果失败的话,则执行performClick
方法,到这一步,终于到了执行了Clic事件,如果设置有onclickListener
,将会被调用; - 接着,如果
mUnsetPressedState
为null的话,则创建一个UnsetPressedState
,若prepressed
为true,则延时执行mUnsetPressedState
,否则将mUnsetPressedState
直接post,如果失败则mUnsetPressedState.run()
,也就是说,无论如何mUnsetPressedState
都会执行,接下来我们看下其中的代码:
private final class UnsetPressedState implements Runnable {
@Override
public void run() {
setPressed(false);
}
}
这里,只执行了一个方法 setPressed(false)
,在这个方法中,将会移除mPrivateFlags
中的PFLAG_PRESSED
,然后执行refreshDrawableState
方法,并执行dispatchSetPressed
将setPressed
传递下去;
- 接着,会执行
removeTapCallback
,移除TapCallback; - 最后会将
mIgnoreNextUpEvent
状态置为false;
总结
至此,两节的事件分发已经告一段落,欢迎同学们指正,沟通,学习.
网友评论