View、ViewGroup的事件分发机制

1、事件概念

    当发生点击事件时,大致的调用顺序是先调用最外层View的dispatchTouchEvent方法,然后调用onInterceptTouchEvent方法,再调用onTouchEvent方法;

    分发、拦截、消费,一个事件的所经历的就是这些处理的组合;

    Activity和View没有onInterceptTouchEvent事件;

1.1、分发

    表示事件是否会继续分发出去,默认返回false,返回true时表示事件不会再继续分发,甚至都不会分发到自身的onTouchEvent方法;

1.2、拦截

    对事件传递做拦截,表示当前层级的View需要处理这个事件,将事件拦截下来,直接派给自己的onTouchEvent方法去处理,如果onTouchEvent方法处理了并且返回true,这个事件就结束了,如果onTouchEvent方法返回false,该事件还会继续传递到上层ViewGroup的onTouchEvent方发去处理;

1.3、消费

    消费事件,如果该方法返回了true,表示对事件消费掉了,事件终止,如果返回false,事件会继续传递给上层ViewGroup方法处理;

2、关键方法

2.1、dispatchTouchEvent

    分发事件,当该方法返回true时,该View不会继续分发事件,包括该事件不会继续分发到该View的onInterceptTouchEvent方法和onTouchEvent方法;

2.2、onInterceptTouchEvent

    拦截事件的传递,是否会继续向子View、子ViewGroup传递,当该方法返回true时,事件不会继续向子View、子ViewGroup传递,相当于父级View把事件在此处截断了;

2.3、onTouchEvent

    消费事件,对点击事件做相应的点击响应处理,具体执行点击后的操作,如果子View不做处理,即返回false,该事件还会继续传递到父View的onTouchEvent方法去处理,直到传递到组外层;

    如果该方法返回true,表示这个事件被消费掉了,这个事件就此终止了,不会再有任何传递;

    对于Activity的onTouchEvent事件,如果内部的控件没有对事件做任何处理,事件最终都会回到Activity的onTouchEvent方法去处理;

3、调用流程图

View、ViewGroup的事件分发机制_第1张图片
View、ViewGroup的事件分发机制_第2张图片
View、ViewGroup的事件分发机制_第3张图片

4、源码

4.1、dispatchTouchEvent

4.1.1、Activity

// Activity
public boolean dispatchTouchEvent(MotionEvent ev) {
  if (ev.getAction() == MotionEvent.ACTION_DOWN) {
    onUserInteraction();
  }
  if (getWindow().superDispatchTouchEvent(ev)) {
    return true;
  }
  return onTouchEvent(ev);
}
​
public Window getWindow() {
  return mWindow;
}
​
// attach方法中初始化mWindow对象
final void attach(Context context, ActivityThread aThread, ...) {
  ...
  mWindow = new PhoneWindow(this, window, activityConfigCallback);
  ...
}
​
// PhoneWindow
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
  return mDecor.superDispatchTouchEvent(event);
}
​
// DecorView
public boolean superDispatchTouchEvent(MotionEvent event) {
  return super.dispatchTouchEvent(event);
}

    Activity中的dispatchTouchEvent()方法中首先判断点击事件是否为按下,并调用onUserInteraction()方法,该方法为一个空实现;

    其次会执行window的superDispatchTouchEvent()方法,在Activity的attach()方法中mWindow是new的一个PhoneWindow对象,在PhoneWindow中又是调用DecorView的superDispatchTouchEvent()方法,DecorView是一个继承自FrameLayout的类,所以他调用的父类的dispatchTouchEvent()方法将追溯到ViewGroup的dispatchTouchEvent()方法中,当子View和ViewGroup都不处理事件,即dispatchTouchEvent()方法都返回false,则会去调用Activity的onTouchEvent()方法处理事件;

4.1.2、ViewGroup

@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);
  }
  ...
}

    首先判断事件的焦点处理,输入事件响应,如果有输入焦点在,则交给输入去执行OnTouchEvent()事件;

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();
  }
  ...
}

    其次判断事件是否符合应用安全策略,将不符合的事件过滤掉;

    当事件是ACTION_DOWN时,调用cancelAndClearTouchTargets()方法清除掉所有关联的目标,即按下事件被认为是一整个事件的开始,并且通过调用resetTouchState()方法重置触摸事件的状态为一个新的周期;

    这里也会重置FLAG_DISALLOW_INTERCEPT这个标记位,这个标记位的作用是决定ViewGroup是否拦截除ACTION_DOWN之外的事件,无法拦截ACTION_DOWN事件,因为在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;
}
​
// 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);
}

    接着判断是否需要拦截,当事件不是ACTION_DOWN并且mFirstTouchTarget为空时,直接返回为true,表示该ViewGroup拦截下来了该事件,说明如果拦截,ViewGroup只能拦截到ACTION_DOWN事件,mFirstTouchTarget为空表示该ViewGroup没有子View去处理事件,所以自己拦截下来;

    当ACTION_DWON或者mFirstTouchTarget不为空时,判断mGroupFlags & FLAG_DISALLOW_INTERCEPT,mGroupFlags是View的标记,FLAG_DISALLOW_INTERCEPT如果该变量设置了,说明该ViewGroup不该拦截事件,返回false,否则就会去调用ViewGroup的onInterceptTouchEvent()方法,ev.setAction(action)重置事件的action,在拦截方法中如果action有发生改变;

    接着如果该事件被拦截,并且mFirstTouchTarget不为空(即事件被子View消费),将该事件的可访问性焦点标记为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 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 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 (!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;
    }
  }
}

    接下来会去遍历子View,将事件分发到子View处理,判断子View是有可访问性焦点并且焦点在子View本身、通过调用canViewReceivePointerEvents()方法和isTransformedTouchPointInView()方法判断View是否可以接受事件(满足两个条件:事件发生在View的区域,子View没有正在播放的动画)、调用dispatchTransformedTouchEvent()方法筛选出可以接受事件的子View,结束循环,事件成功交给子View;

    在调用dispatchTransformedTouchEvent()方法是,第三个参数不为空,即子View不为空时,调用子View的dispatchTouchEvent()方法去处理;

private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
  final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
  target.next = mFirstTouchTarget;
  mFirstTouchTarget = target;
  return target;
}

    调用addTouchEvent()方法,为mFirstTouchTarget赋值;

// 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;
  }
}

    如果没有找到合适的可以接受事件的子View,则mFirstTouchTarget没有赋值,则ViewGroup自己调用dispatchTransformedTouchEvent()方法处理,第三个参数View child为null,查看该方法,当child为null时,调用父类的dispatchTouchEvent()方法,即调用View的dispatchTouchEvent()方法;

4.1.3、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);
  }
  ...
}

    View的dispatchTouchEvent()方法,会先判断该事件是否为带有焦点处理的,例如EditText的输入响应、Button的点击响应等,如果没有需要处理的则直接返回false,如果有则设置相关标记,继续进行正常的事件派发;

if (mInputEventConsistencyVerifier != null) {
  mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}

    检查是否有输入性的事件,如果有,表示该View属于一个输入类型的View,则去调用该输入序列的onTouchEvent()方法去处理输入事件;

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;
  }
}
​
public boolean onFilterTouchEventForSecurity(MotionEvent event) {
  //noinspection RedundantIfStatement
  if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
    // Window is obscured, drop this touch.
    return false;
  }
  return true;
}

    接着调用onFilterTouchEventForSecurity()方法过滤不符合应用安全策略的事件,如果可以继续被分发则返回true,否则返回false;

    接着判断View的各种状态,以及是否被滚动条事件消费掉等,handleScrollBarDragging()方法处理拖动滚动条事件,当该方法处理完之后返回true表示消费掉该事件;

    接着判断mOnTouchListener是否为空,不为空表示用户自定义了OnTouchEvent事件(通过调用setOnTouchListener()方法),则会调用OnTouchListener的onTouchEvent()方法去处理事情并返回,所以设置OnTouchListener的优先级要高于本身的OnTouchEvent事件;

    最后判断本身OnTouchEvent()方法处理返回;

if (!result && mInputEventConsistencyVerifier != null) {
  mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}

    如果最终事件没有处理并且是输入控件,则将该输入序列挂起为未处理,并重置该事件需要被忽略;

if (actionMasked == MotionEvent.ACTION_UP ||
    actionMasked == MotionEvent.ACTION_CANCEL ||
    (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
  stopNestedScroll();
}

    最终手势事件结束并且处理结果为false时,调用stopNestedScroll()方法,停止正在进行的嵌套滚动;

4.2、onInterceptTouchEvent

4.2.1、ViewGroup

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;
}

    该方法判断是否需要对事件进行拦截下来处理,通过判断事件的来源、是否为ACTION_DOWN事件、是否是Button按钮按下以及滚动条事件等,来决定是否需要将该事件拦截下来;

4.3、onTouchEvent

4.3.1、Activity

public boolean onTouchEvent(MotionEvent event) {
  if (mWindow.shouldCloseOnTouch(this, event)) {
    finish();
    return true;
  }
  return false;
}

    当屏幕触摸事件没有被任何子View消费时,最终会调用该方法来处理,该方法默认实现是返回为false;

4.3.2、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;
    }
  }
  ...
}

    对View的各种标识进行判断,该View为可点击、长按的状态,clickable为true,当View为禁用点击时DISABLED,也会处理该事件,只是没有具体的响应,将状态设置为未点击,并刷新Drawable状态;

    如果设置了触摸代理,即mTouchDelegate不为空,则交给mTouchDelegate对象去处理OnTouchEvent()事件并返回true,表示事件被消费,不再继续传递;

case MotionEvent.ACTION_UP:
  mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
  if ((viewFlags & TOOLTIP) == TOOLTIP) {
    handleTooltipUp();
  }
  if (!clickable) {
    removeTapCallback();
    ...
  }
  boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
  if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
    ...
    if (prepressed) {
      ...
      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) {
        ...
        if (mPerformClick == null) {
          mPerformClick = new PerformClick();
        }
        if (!post(mPerformClick)) {
          performClickInternal();
        }
      }
    }
    ...
    if (prepressed) {
      postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration());
    } else if (!post(mUnsetPressedState)) {
      // If the post failed, unpress right now
      mUnsetPressedState.run();
    }
​
    removeTapCallback();
  }
  mIgnoreNextUpEvent = false;
  break;

    如果该View有长按提示效果,则先处理掉该长按提示事件;

    如果当前View是不可点击的,则清除掉View的各种相关状态;

    PFLAG_PREPRESSED状态为嵌套滚动View,如果View被嵌套在一个滚动的View中,会检查其父View是否拦截事件,如果父View没有拦截则开始处理,调用setPressed()方法设置按下状态让用户明确感受到;

    判断mHasPerformedLongPress和mIgnoreNextUpEvent是否为处理过长按事件,如果不是长按,调用removeLongPressCallback()方法移除掉长按事件的回调,接着开启一个子线程(new PerformClick())去执行click事件,如果异步执行失败,则直接同步执行,接着调用ViewConfiguration.getPressedStateDuration()获得按下效果的显示时间设置View的显示状态(API 28 显示时间为64ms),同样post失败之后直接调用,移除掉Tap的回调,重置View状态;

    performClickInternal()方法中调用performClick()方法,在这里会判断onClickListener是否为空,不为空则执行onClickListener的onClick()方法,即用户设置的onClickListener事件,优先级最低;

case MotionEvent.ACTION_DOWN:
  if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
    mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
  }
  mHasPerformedLongPress = false;
​
  if (!clickable) {
    checkForLongClick(0, x, y);
    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;

    按下事件,如果View不可点击,检查长按事件,如果是则直接跳出,接着会检查是否在滚动容器中,如果是设置mPrivateFlags状态,接着new CheckForTap去检查是Tap还是长按事件,如果在滚动View中嵌套,则通过ViewConfiguration.getTapTimeout()去获取延迟返回时间,设置在规定时间内,如果用户没有移动则说明是点击事件(API 28中为100ms);

case MotionEvent.ACTION_CANCEL:
  if (clickable) {
    setPressed(false);
  }
  removeTapCallback();
  removeLongPressCallback();
  mInContextButtonPress = false;
  mHasPerformedLongPress = false;
  mIgnoreNextUpEvent = false;
  mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
  break;

    取消手势,重置View所有状态;

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;

    移动手势,通过调用drawableHotspotChanged()方法,实时更新传递移动的坐标位置;

    接着判断当前移动的手势是否在View中,如果移除手指,则移除掉对应的回调;

本文参考:
《Android开发艺术探索》
2019移动开发者峰会-陈冰-Android移动端手势交互原理

你可能感兴趣的:(Android开发,源码)