个人笔记---view的事件分发机制

前言

在如今这个拼颜值的社会,app不光要运行流畅,更要用优美的界面来吸引用户,有时候总感觉官方提供的控件远远不能满足我们的需求,我们需要自己动手去自定义一些view。

说到自定义view,相信很多人都比较头疼了,当然我也不擅长这个。最让我头疼的应该就算是view的事件分发了(说了这么多废话,终于进入正题了),废话不多说,本文会对view的事件分发机制做一个详细的说明。

当我们点击了一个按钮,系统内部到底发生了什么

一个完整的点击事件是有多个MotionEvent事件构成的,当手指按下屏幕,会伴随着一个ACTION_DOWN事件;手指在屏幕上滑动,会伴随一个或多个ACTION_MOVE事件;手指抬起则会产生一个ACTION_UP事件,从ACTION_DOWN到ACTION_UP成为一个事件序列

Activity作为四大组件之一,我们与app的交互都要依赖与它,点击事件自然是最先传递到Activity的dispatchTouchEvent中(talk is cheap,上代码)

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

Activity中具体的分发工作交给了Window,如果返回true,整个事件循环就结束了,返回false则代表没人处理,所有的onTouchEvent都返回false,那么activity的onTouchEvent会被调用。

那么看一下Window中是如何分发事件的

public abstract boolean superDispatchTouchEvent(MotionEvent event);

Window中的分发事件的方法是一个抽象方法,我们就要找到哪里实现了这个方法。而这个方法的实现是在PhoneWindow中,PhoneWindow是Window的唯一实现,看PhoneWindow中的代码

@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

代码比较清晰,PhoneWindow将事件又传递给了DectorView,这里先看一下Activity,Window和Decorview之间的关系

每个Activity都对应一个Window,这个Window窗口的唯一实例就是PhoneWindow,PhoneWindow对应的布局则是DecorView,它继承自FrameLayout,是一个ViewGroup,DecorView里面又分为两部分,actionBar和contentView,而contentView就是我们在Activity中setContentView设置的布局。

通过这个图,我们也了解了他们之间的关系,下面继续说事件的分发传递。

此时事件已经传递给DecorView,它其实就是一个ViewGroup,

public class DecorView extends FrameLayout implements ... {
    public boolean superDispatchTouchEvent(MotionEvent event) {
            return super.dispatchTouchEvent(event);
    }
}

从这里开始,事件就传递到了顶级View,而我们最关注的点就是从顶级View开始到各个子view之间的事件是如何分发的。一般顶级View都是ViewGroup,会调用ViewGroup的dispatchTouchEvent方法,这里只看一下关键代码

if (actionMasked == MotionEvent.ACTION_DOWN) {
       cancelAndClearTouchTargets(ev);
       resetTouchState();
}
final boolean intercepted;
//分两种情况拦截事件,事件类型为ACTION_DOWN或者mFirstTouchTarget != null
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 {
       intercepted = true;
}

当事件为ACTION_DOWN时,首先会重设一些状态,resetTouchState()方法会将mFirstTouchTarget置为空,FLAG_DISALLOW_INTERCEPT重置,
ViewGroup是否拦截事件分为两种情况,当事件为ACTION_DOWN或mFirstTouchTarget != null时,这个mFirstTouchTarget是什么?mFirstTouchTarget是判断是否有子view消费了当前事件,若消费则会通过newTouchTarget = addTouchTarget(child, idBitsToAssign)对mFirstTouchTarget赋值,具体会在下面说明

接下来看一下FLAG_DISALLOW_INTERCEPT这个参数,FLAG_DISALLOW_INTERCEPT可以通过requestDisallowInterceptTouchEvent方法设置,一般用于子view,如果子view设置了FLAG_DISALLOW_INTERCEPT,ViewGroup将无法拦截除ACTION_DOWN以外的事件

为什么是除了ACTION_DOWN以外的事件?上面说了,ACTION_DOWN会重置FLAG_DISALLOW_INTERCEPT,导致子view设置的这个标记位无效,ViewGroup总是调用onInterceptedTouchEvent询问是否拦截事件。

222.png

除去ACTION_DOWN事件, 若子view设置了FLAG_DISALLOW_INTERCEPT,intercept = false, 不拦截;否则调用onInterceptTouchEvent询问是否拦截事件, 默认返回false,事件交由子view处理,接着看代码,

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;
    }
    //子view是否可见或是否正在播放动画
    if (!canViewReceivePointerEvents(child)
            //点击区域是否落在子view内部
            || !isTransformedTouchPointInView(x, y, child, null)) {
         ev.setTargetAccessibilityFocus(false);
         continue;
    }
    //如果已经有子view处理过事件序列中的一个事件,则newTouchTarget不为空,跳出当前循环
    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);
    //调用child的diapatchTouchEvent方法
    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);
}

遍历ViewGroup的子view,子view如果不可见并且没有播放动画,并且点击区域没有落在子view区域内部,继续遍历下一个子view;接下来这段代码比较有意思,

private TouchTarget getTouchTarget(@NonNull View child) {
        for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
            if (target.child == child) {
                return target;
            }
        }
        return null;
    }

分发事件时会先判断newTouchTarget是否为空,那么这个newTouchTarget何时为空,何时不为空呢。还记得本文上面有提到addTouchTarget方法么,事实上mFirstTouchTarget也是在那个时候被赋值的,当某个子view处理了ACTION_DOWN事件,mFirstTouchTarget被设置为当前子view,当这一个事件序列的其他事件分发时,此时再去获取newTouchTarget时,newTouchTarget显然不为空,直接跳出循环,当然首次处理时,mFirstTouchTarget为空,newTouchTarget也为空。

接下来就要了分发过程中最重要的步骤了,放大招
通过将遍历到的子view传入dispatchTransformedTouchEvent方法中(此时child不为空),我们也看一下这个方法的核心源码,

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        ...
        final boolean handled;
        ...
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            ...
            handled = child.dispatchTouchEvent(transformedEvent);
        }
        return handled;
    }

方法中通过child是否为空分为两种情况,当child不为空时,事件就交由子view去处理,这样就完成了一轮事件的分发,如果子view的dispatchTouchEvent返回true,终于在这里看到了addTouchTarget方法,是的,mFirstTouchTarget就是在这里赋值的,结束以后跳出循环。

 newTouchTarget = addTouchTarget(child, idBitsToAssign);


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

如果遍历完以后mFirstTouchTarget仍然为空,说明子view的dispatchTouchEvent返回了false或者ViewGroup内没有子元素,此时ViewGroup会自己处理这个点击事件

if (mFirstTouchTarget == null) {
    //传入的child为null,说明没有子view去处理这个事件
     handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);
}

child == null时,handle = super.dispatchTouchEvent(event),到此,事件就转到了View的dispatchTouchEvent方法中。

那么View是怎么分发事件的

既然到了View,还是要show一下源码

public boolean dispatchTouchEvent(MotionEvent event) {
        ...
        boolean result = false;
        ...
        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;
    }

View的dispatchTouchEvent方法中就比ViewGroup的精简了很多,因为View是一个单独的元素,它没有子view的概念,省去了遍历子view分发事件的步骤。从代码可以看出View对事件的处理,首先判断view有没有设置OnTouchListener,如果设置了并且onTouch方法返回true,那么onTouchEvent方法就不会被调用了,若返回false则调用OnTouchEvent方法。接着我们看一下onTouchEvent方法

public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();
        //clickable和long_clickable只要有一个为true,就会消费点击事件
        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.
           // 此处说明了只要clickable为true,不可用状态也会消费点击事件
            return clickable;
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        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)) {
                                    //ACTION_UP事件触发performClick()
                                    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;
                ...
            }

            return true;
        }

        return false;
    }

通过View的OnTouchEvent方法不难看出,当一个View的clickable或longClickable为true时,即使它处于不可用的状态,也依然会消费点击事件返回true;在ACTION_UP事件发生时,会触发performClick()方法,看一下这个方法的代码

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;
        }
        ...
        return result;
    }

如果View设置了OnClickLisener,就会调用它的onClick方法,到这里,View的事件分发就结束了,好像还差点什么。

结论

1.一个事件序列以一个ACTION_DOWN开始,中间可能伴随着多个ACTION_MOVE,最后以一个ACTION_UP结束
2.一个事件序列只能被一个view拦截并消费掉,若一个View拦截了ACTION_DOWN,则必定会设置mFirstTouchTarget,其它事件会通过通过getTouchTarget.child获取到子view并交由它处理
3.ViewGroup默认不拦截任何事件
4.View没有onInterceptedTouchEvent方法,View是单独元素,一旦有点击事件传递给它,就会调用它的onTouchEvent方法
5.View 的onTouchEvent方法默认会消耗掉事件(返回true),除非它是不可点击的
6.View的enable属性不影响onTouchEvent的返回值,只要clickable和longclickable有一个为true,它的onTouchEvent就返回true
7.onClick发生的前提是当前view是可点击的,通过setOnClickListener或setOnLongClickListener会默认将clickable或longclickable置为true
8.OnTouchListener, onTouchEvent, onClickListener之前的优先级 OnTouchListener > onTouchEvent > onClickListener


个人能力有限,如有错误,欢迎指正

你可能感兴趣的:(个人笔记---view的事件分发机制)