学习笔记:View的事件体系4:View的事件分发机制

来源:互联网 发布:安卓软件优化网站 编辑:程序博客网 时间:2024/06/03 19:45

所谓点击事件的事件分发,其实就是对MotionEvent事件的分发过程,即当一个MotionEvent 产生了以后,系统需要把这个事件传递给一个具体的View,而这个传递过程就是事件分发。点击事件的分发过程由三个很重要的方法来共同完成:dispatchTouchEvent,onInterceptTouchEvent和onTouchEvent,

public boolean dispathcTouchEvent(MotionEvent ev)

用来进行事件的分发。如果事件能够传递给当前View,那么此方法一定会被调用,返回结果受当前View的onTouchEvent和下级View的dispathTouchEvent方法的影响,表示是否消耗当前事件。

public boolean onInterceptTouchEvent(MotionEvent event)

在上述方法内部调用,用来判断是否拦截某个事件,如果当前View拦截了某个事件,那么在同一个事件序列当中,此方法不会被再次调用,返回结果表示是否拦截当前事件。

public boolean onTouchEvent(MotionEvent event)

在dispatchTouchEvent方法中调用,用来处理点击事件,返回结果表示是否消耗当前事件,如果不消耗,则在同一个事件序列中,当前View无法再次接收到事件。

伪代码:

 public boolean dispatchTouchEvent(MotionEvent event){    boolean consume=false;    if(onInterceptTouchEvent(event)){        consume=onTouchEvent(event);    }else{        consume=child.dispatchTouchEvent(event);    }    return consume;}

对于一个ViewGroup来说,点击事件产生后,首先传递给它,这里它的dispatchTouchEvent就会被调用,如果这个ViewGroup的onInterceptTouchEvent返回的是true,表示要拦截此事件,接着事件就交给了ViewGroup处理,然后调用onTouchEvent方法。如果onInterceptTouchEvent方法返回了false,说明当前不拦截此事件,将会调用子视图的dispatchTouchEvent,如此反复直到事件最终被处理。
视图的优先级
onTouch>onTouchEvent>onClickListener
点击事件的传递过程遵循如下顺序:Activity->Window->View

点击事件的分发过程(源码)
一个点击操作发生时,事件最先传递给当前Activity,由Activity的dispatchTouchEvent来进行事件派发,具体工作是由Activity内部的Window来完成,Window会将事件传递给decor view
源码:Activity#dispatchTouchEvent

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

点击事件用MotionEvent来表示, 当一个点击操作发生时,事件最先传给前Activity,由Activity的 dispatchTouchEvent来进行派发,具体的工作是由Activity内部的Window来完成的,Window会将事件传递给decor view,decor view一般就是当前界面的底层容器。
首先事件开始交给Activity所附属的Window进行分发,如果返回true,事件的循环就结束了,如果返回false,就意味着没从处理,所有的View的onTouchEvent都返回false,那么Activity 的onTouchEvent()就会被调用。 (getWindow().superDispatchTouchEvent(ev)是将事件派发给子类运行,如果都没有人处理这个事件,将交给Activity的onTouvhEvent(ev)来处理此事件。)
Window的superDispatchTouchEvent()是一个抽象方法,Window的实现类是PhoneWindow,调用PhoneWindow#superDispatchTouchEvent

      //PhoneWindow#superDispatchTouchEvent     public boolean superDispatchTouchEvent(MotionEvent event){        return mDecor.superDispatchTouchEvent(event);    }

可以看出,PhoneWindow将事件直接传递给了DecorView 由于他继承自FrameLayout 而 FrameLayout继承 ViewGroup 所以他的事件分发由ViewGroup完成.

顶级View对点击事件的分发过程:
点击到达顶级View以后,会调用ViewGroup的DispatchTouchEvent方法,如果顶级的ViewGroup拦截此事件即onInterceptTouchEvent返回true,则由ViewGroup处理,这时候mOntouchListener被设置,则onTouch被调用,否则onTouchEvent会被调用,如果ViewGroup不拦截此事件,则事件传给他它所在的点击事件链上的子View 接下来传递过程和顶级View一致,直到完成整个事件的分发。
看下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;            }

此部分检查当前时候拦截此事件,注意几点:
1:actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null
这个条件为假时候 直接交给当前的ViewGroup处理此事件,必须两个条件都不满足,那么mFirstTouchTarget!=null是什么意思呢?当事件由ViewGroup的子元素成功处理时,mFirstTouchTarget会被赋值并且指向子元素,换句话说,当ViewGroup不拦截此事件交由子元素处理时,mFirstTouchTarget!=null就不成立了。反过来,一旦事件由当前ViewGroup拦截时,mFirstTouchTarget!=null就不成立了。那么当ACTION_MOVE和ACTION_DOWN到来时, if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) 为false 将导致ViewGroup的的onInterceptTouchEvent不会被调用,并且一序列中的其他事件都会默认交给它处理。
2:FLAG_DISALLOW_INTERCEPT标记位,这个标记位通过requestDisallowInterceptTouchEvent方法来设置,一般用于子View中,FLAG_DISALLOW_INTERCEPT 一旦设置后,ViewGroup将无法拦截除了ACTION_DOWN以外的其他点击事件。

3 intercepted = onInterceptTouchEvent(ev); 如果onInterceptTouchEvent(ev)返回true那么 intercepted =true,

 if (!canceled && !intercepted) {                // If the event is targeting accessiiblity 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);                            // 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;                            }

首先遍历ViewGroup的所有子元素,然后判断子元素是否接收到点击事件,然后调用dispatchTransformedTouchEvent方法,这个方法调用子元素的dispatchTouchEvent方法,从而完成了一轮事件分发。

if (child == null) {                handled = super.dispatchTouchEvent(event);            } else {                handled = child.dispatchTouchEvent(event);            }
0 0