前面写过一篇文章,说了下事件分发机制的方法和大致流程,本文尝试从源码的角度一层一层的看下分发机制。
源码的查看:https://www.androidos.net.cn/sourcecode(可能是我下的源码有问题,部分方法我是在线查看的)
Activity的事件分发机制
我们从activity的dispatchTouchEvent方法进行源码分析:
-
public boolean dispatchTouchEvent(MotionEvent ev) {
-
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
-
onUserInteraction();
-
}
-
if (getWindow().superDispatchTouchEvent(ev)) {
-
return
true;
-
}
-
return onTouchEvent(ev);
-
}
点进去看到,onUserInteraction是个空方法,这里是用来实现屏保功能的,当activity位于栈顶时,触屏点击home、menu、back会触发。
-
public void onUserInteraction() {
-
}
然后我们来看第二个判断
-
if (getWindow().superDispatchTouchEvent(ev)) {
-
return
true;
-
}
继续往下看,
public abstract boolean superDispatchTouchEvent(MotionEvent event);
这玩意是个抽象方法,对应的Window也是个抽象类,我们能找到PhoneWindow,
-
@Override
-
public boolean superDispatchTouchEvent(MotionEvent event) {
-
return mDecor.superDispatchTouchEvent(event);
-
}
然后我们在看下这个mDecor是啥,
找到这个类
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks
他是继承FrameLayout的,也就是mDecor.SuperDispatchTouchEvent即等同于Viegroup的分发机制。(即事件从activity传递到了viewgroup)
再看最后一个onTouch方法,
-
public boolean onTouchEvent(MotionEvent event) {
-
if (mWindow.shouldCloseOnTouch(
this,
event)) {
-
finish();
-
return
true;
-
}
-
-
return
false;
-
}
这里默认返回false,就是不处理,向下层分发,那我们来看下这个判断里面。
-
public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
-
final boolean isOutside =
-
event.getAction() == MotionEvent.ACTION_DOWN && isOutOfBounds(context,
event)
-
||
event.getAction() == MotionEvent.ACTION_OUTSIDE;
-
if (mCloseOnTouchOutside && peekDecorView() !=
null && isOutside) {
-
return
true;
-
}
-
return
false;
-
}
这里主要判断是否在边界外,在即消费事件,返回true,分发结束,反之返回false,activity层的分发也结束,扔给viewgroup继续分发,直到被消费。
viewgroup的分发机制
我们从ViewGroup的dispatchTouchEvent方法进行源码分析:
-
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<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);
代码很长,挑一点看看(不完整,感兴趣的自己查看),就是判断事件没有取消也没有被拦截,然后给viewgroup内的子view进行遍历,继续看重点
-
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;
-
}
我们给这个dispatchTransformedTouchEvent点进去,
-
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;
-
}
这里面进行了判断,事件传递给了view(即child)进行分发,或者给他的上一层viewgroup进行分发,直到事件分发结束,即被消费。
回过头来,我们看拦截的判断
-
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;
-
}
这里面的事件被拦截即 mFirsTouchTarget!=null不成立,即不拦截,mFirsTouchTarget!=null,disallowIntercept表示是否允许被拦截,是可以用代码来控制的,经过判断,允许被拦截再调用拦截的方法,
-
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;
-
}
这里面进行多个判断,默认返回false,即不拦截。拦截的要求大致上,这个事件是来自使用者的输入、是down事件、这个是按钮、点击的事件只在viewgroup内。一旦拦截了,它就会向它的父类分发,也就是view的分发,但执行ViewGroup的onTouch() ->> onTouchEvent() ->> performClick() ->> onClick(),即自己处理该事件,事件不会往下传递(具体请参考View事件的分发机制中的View.dispatchTouchEvent())。(可以理解为虽然是个viewgroup,但里面并没有子view,所以事件分发相当于view的事件分发),这个地方要注意。
View的事件分发机制
我们从View的dispatchTouchEvent方法进行源码分析:(源码可能下的有点问题,我们在线看下)
-
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;
-
}
-
}
它返回的是result,即决定是否继续分发,返回true,即事件被消费,false即要调用onTouch方法。返回true有三种情况
1. view是可点击的且handleScrollBarDragging
看下源码(太长,看下什么时候返回true)
-
* @
return
true
if the
event was handled
as a scroll bar dragging,
false otherwise.
-
*/
-
protected boolean handleScrollBarDragging(MotionEvent event) {
翻译:如果作为一个滚动条拖动事件处理返回true
2. view可点击且onTouch事件不为空
3. onTouch事件返回true
下面看下onTouchEvent方法
-
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();
-
}
即view可点击进入switch判断具体DOWN、UP等事件,重点看下这个
-
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;
-
}
根据代码我们知道只要我们通过setOnClickListener()为控件View注册1个点击事件,那么就会给mOnClickListener变量赋值(即不为空),则会往下回调onClick() & performClick()返回true。即调用onTouch事件要调用performClick事件,当这些执行完才能执行我们常见的onClick事件,至此,事件分发结束。
核心结论
事件逐层分发,判断是否拦截,拦截就本层消费,否则向下分发,直至被消费。
写在最后
宣传一下自己的技术交流群:589780530
里面有妹子 里面有妹子 里面有妹子 重要的事情说三遍,另外还有Go/C/python等其他领域的大佬,欢迎加入