在Android
开发中,事件分发已经成为开发者的必备知识,那么若是面试官让你讲一下对事件分发的理解,你将会怎么去讲呢?面试
咱们都在说的事件分发的本质是什么呢?bash
咱们都知道事件的传递和分发都是在手指触发屏幕的一瞬间开始,那么在触发后,系统会作出什么反应呢?app
接下来,让咱们一一揭开这层神秘的面纱。ide
全部的事件发生的起源就在于Touch
事件,咱们的在屏幕上的操做动做,能够分为四种:post
动做 | 描述 |
---|---|
MotionEvent.ACTION_DOWN | 在页面上按下某个位置 |
MotionEvent.ACTION_MOVE | 手指在页面上进行移动(滑动) |
MotionEvent.ACTION_UP | 手指抬起 |
MotionEvent.ACTION_CANCEL | 结束事件(在ACTION_UP后会执行) |
从用户角度来讲,咱们手指接触的地方是一个页面,也就是咱们所说的UI
,UI从上到下依次是Activity
、ViewGroup
、View
。动画
有可能一个ViewGroup里还有一个或者多个ViewGroup,这里咱们只哪最简单的页面构造来分析。ui
那么显然得知,事件的传递机制就是从上到下的,依次就是 Activity
-> ViewGroup
-> View
this
事件的分发涉及到三个方法:spa
dispathTouchEvent
代理
onInterceptTouchEvent
onTouchEvent
它们三者的调用关系能够用一个经典的例子来讲明:
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean consume = false;
if(onInterceptTouchEvent(ev)) {
consume = onTouchEvent(ev)
} else {
consume = child.dispatchTouchEvent(ev)
}
return consume;
}
复制代码
事件的传递首先从Activity
开始,直到有一个控件处理了这个事件。咱们来看下源码中作了些什么。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
复制代码
一、onUserInteraction
是一个空方法。
二、由上边代码能够看出,Activity会发送给依附的Window来处理,若是Window中没有处理这个事件,就会交给Activity的onTouchEvent去处理。
那么这个getWindow是什么呢?
Window是一个抽象类,它的实现类是PhoneWindow
。
PhoneWindow
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
复制代码
DecorView
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
复制代码
DecorView是Activity的顶层View,继承FrameLayout
,也就是说Activity中的点击事件会传递到ViewGroup中,咱们来看下ViewGroup中的分发机制,这也是本篇中比较难的点。
dispatchTouchEvent
// 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;
}
复制代码
这是dispatchTouchEvent中的一段逻辑,代码比较多咱们一点点分析。
由上面代码咱们能够看到ViewGroup
的拦截首先要知足两个条件:actionMasked == MotionEvent.ACTION_DOWN
以及mFirstTouchTarget != null
,第一个很好理解,第二个是什么呢?这里咱们留一个疑问,接着往下看。
disallowIntercope
中的关键在FLAG_DISALLOW_INTERCEPT
标志位,若是这个标志位被设置了,那么将不会被拦截。看下以前的一段代码:
// 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
的话,就会重置状态,包括FLAG_DISALLOW_INTERCEPT
,因此设置了FLAG_DISALLOW_INTERCEPT
将不会拦截除了ACTION_DOWN
以外的事件。
接下来咱们看下不拦截以后的处理逻辑:
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 = 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;
复制代码
这段比较长,咱们来找一些重要的逻辑看下,首先遍历全部的子View,判断它们是否是处理了这个事件。
判断的依据有三个:
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
复制代码
一、当前child是否可得到焦点。
二、当前child是否正在执行动画。
三、当前事件的坐标是否在child的区域内。
若是这些都知足,就会调用dispatchTransformedTouchEvent
方法来将事件分发给child去处理。
dispatchTransformedTouchEvent
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
复制代码
若是有child处理了事件,则addTouchTarget
,并跳出循环
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
复制代码
看了addTouchTarget
方法是否是就能够解答上面的疑问了?
mFirstTouchTarget
是一个单链表,指向处理了事件的child,它的赋值与否直接影响了ViewGroup的拦截逻辑。
接着往下看:
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
复制代码
若是全部的child都没有处理事件,那么就会走super.dispatchTouchEvent(event)
.
ViewGroup的super固然就是View了,看看,是否是最终会走到View的处理逻辑里。
View的处理逻辑就相对来讲,简单多了,咱们来看下:
public boolean dispatchTouchEvent(MotionEvent event) {
....
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;
}
}
...
return result;
}
复制代码
看上面的代码,咱们发现它会先判断OnTouchListener
,若是设置了OnTouchListener
,就会走里面的onTouch
方法,不然才会走onTouchEvent
咱们来看下onTouchEvent
方法:
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; } } 复制代码
首先会判断是否是不可用状态,若是是不可用状态也是会消费事件的,其次的代理的判断。
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(); } } } ... 复制代码
只要是点击状态是CLICKABLE
或者LONG_CLICKABLE
都会消费事件,最终会走到performClickInternal
, 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
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
复制代码
咱们每一个View的默认LONG_CLICKABLE
都是false的,CLICKABLE
大都也是false的,看上面代码可知,在 setOnClickListener
会将CLICKABLE
设置为true。
到这里,事件分发的机制就了解完了,你是否是对刚开始提出的问题有了答案了呢?