相信伙伴们在日常的开发工作中,一定会遇到事件冲突的问题,e.g. 一个页面当手指滑动的时候,会翻到下一页;点击的时候,需要响应页面中的元素点击事件,这个时候如果没有处理滑动事件,可能遇到的问题就是在滑动翻页的时候却只响应了点击事件,这个就是点击事件与滑动事件的冲突。其实还有很多常见的经典事件,e.g. RecyclerView嵌套滑动,ViewPager与RecyclerView嵌套滑动等,所以这个时候我们需要对事件分发非常了解,才能针对需求做相应的处理。
1 Android 事件分发机制
这是一个老生常谈的问题,相信伙伴们都了解常见的Android事件类型:ACTION_DOWN、ACTION_MOVE、ACTION_UP,分别代表手指按下屏幕的事件、手指滑动的事件以及手指抬起的事件,那么从手指按下到事件响应,中间经历了什么呢?我们从Google的源码中去寻找答案。
1.1 事件分发流程
因为对于组件来说,这个事件要么消费要么不消费(事件处理),而对于容器来说,还需要做的一件事就是分发事件,通常是先分发后处理,而View就只是处理事件。
因此在进行事件冲突处理的时候,对于事件是否向下分发给子View消费,就需要在父容器中做拦截,子View仅做事件消费。
如有需要完整版Android进阶学习资料 请点击免费领取
1.2 View的事件消费
首先我们先不看事件是如何分发的,先关注下事件是如何被处理的,在View的dispatchTouchEvent方法中,就包含对事件的处理全过程。
public boolean dispatchTouchEvent(MotionEvent event) {
//......
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;
}
//核心代码1
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//核心代码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;
}
看到dispatchTouchEvent,我们可能会想,这个方法名看着像是分发事件的方法,View不是仅仅消费事件吗,还需要处理分发?其实不是这样的,因为View对于事件可以有选择的,可以选择不处理事件,那么就会往上派给父类去处理这个事件,如果能够消费,那么就在onTouchEvent中处理了。
核心代码1:首先拿到一个ListenerInfo对象,这个对象中标记了这个View设置的监听事件,这里有几个判断条件:
(1)ListenerInfo不为空,而且设置了OnTouchListener监听;
(2)设置了OnTouchListener监听,而且onTouch方法返回了true
这个时候,result设置为true;
核心代码2:如果满足了核心代码1的全部条件,那么核心代码2就不会走到onTouchEvent这个判断条件中,因为result = true不满足条件直接break。
那么如果设置了OnTouchListener监听,而且onTouch方法返回了false,那么result = false,核心代码2就能够执行onTouchEvent方法,我们看下这个方法实现。
public boolean onTouchEvent(MotionEvent event) {
//......
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)) {
performClickInternal();
}
}
}
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(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
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(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
}
break;
//----------注意这里的返回值,clickable为true----------//
return true;
}
//----------注意这里的返回值,clickable为false----------//
return false;
}
这里就是对所有事件的处理,包括但不限于ACTION_DOWN、ACTION_UP,我们需要知道一点就是,View的click事件其实是在ACTION_UP中处理的。我们从上面的源码中可以看出来,在ACTION_UP中有一个方法performClickInternal,具体实现为performClick方法。
public boolean performClick() {
// We still need to call this method to handle the cases where performClick() was called
// externally, instead of through performClickInternal()
notifyAutofillManagerOnClick();
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;
}
在这个方法中,我们貌似看到同样的一段代码,如果设置了OnClickListener监听,那么就会执行onClick方法也就是响应点击事件。
所以通过上面的分析,我们能够了解,如果同一个View同时设置了setOnClickListener和setOnTouchListener,如果setOnTouchListener返回了false,那么点击事件是可以响应的;如果setOnTouchListener返回了true,那么点击事件将不再响应。
binding.tvHello