事件分发机制(二):源码篇

582 阅读6分钟

上篇对整体事件分发流程大致梳理下,有兴趣的朋友可以去看看事件分发机制(一):解惑篇

本篇就基于上篇的知识上,跟着大家走一波事件分发的源码,这样可能大家能够更理解下源码.

Acitvity ## dispatchTouchEvent

事件源头从Activity向下进行分发,点进查看看dispatchTouchEvent代码

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //具体的工作由 Activity 内部的 Window 来完成的。如果返回 true,整个事件循环就结束了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        //如果下面的都没有给消费掉,最后事件只能有自己onTouchEvent消费了
        return onTouchEvent(ev);
    }

代码比较简单,事件从Activity向下分发,如果事件被消费,直接返回True,如果都没有处理消费,只能由自己onTouchEvent自己处理,由此可见,整体事件分发机制就是类似一个U字型的流程,事件由Activity开始分发,到最底层的View,最后回到Activity的onTouchEvent,当然,这之间任何一个地方返回True都能够打断这个流程。

PhoneWindow ## superDispatchTouchEvent

唯一实现Window类的就是PhoneWindow类,所以实际上就是调用PhoneWindow的方法了

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

PhoneWindow将事件直接传递给了 DecorView,熟悉setContentView代码的朋友应该知道,DecorView实际上就是而我们通过 setContentView设置的 View,所以事件最终也是走进了ViewGroup中

ViewGroup ## dispatchTouchEvent

/ ViewGroup.java

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
            ...
        
            // Check for interception.
            final boolean intercepted;
            //如果是ACTION_DOWN,重置mFirstTouchTarget以及FLAG_DISALLOW_INTERCEPT标志位
            if (actionMasked == MotionEvent.ACTION_DOWN) {            
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }
            //这里2个条件,满足1个即可进入判断体内
            //1.当前的事件行为为MotionEvent.ACTION_DOWN
            //2.mFirstTouchTarget对象不为空,这个对象可以理解为当事件由ViewGroup的子元素处理时,那么mFirstTouchTarget指向那个子元素
            if (actionMasked == MotionEven_ACTION_DOWN
                    || mFirstTouchTarget != null) { 
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                   intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); 
                } else {
                    intercepted = false;
                }
            } else {
                intercepted = true;
            }
            
            ...
    }

代码比较长,我们看关键代码,首先第一个判断,如果当前事件状态为ACTION_DOWN,则重置mFirstTouchTarget置位空,以及将FLAG_DISALLOW_INTERCEPT重置。

  • 我们应该还记得,子View可以通过requestDisallowInterceptTouchEvent方法来要求父ViewGroup不拦截事件,实际上就是改变父ViewGroup这里的这个FLAG_DISALLOW_INTERCEPT标志位,但是每次DOWN事件这个标志位会被重置,所以可以得出结论,当这个标志位被requestDisallowInterceptTouchEvent改变后,ViewGroup将无法拦截除了ACTION_DOWN以外的其它点击事件
  • 当事件被拦截之后,上述mFirstTouchTarget解释可以看到,此时mFirstTouchTarget是为空,所以mFirstTouchTarget!=null是不成立的,此时直接intercepted 为True,此处也是验证了上篇的结论,一旦当前View拦截事件,那么同一事件序列的其它事件都不再进行拦截校验,直接交给它处理
  • 对应DOWN事件,ViewGroup每次询问自己的onInterceptTouchEvent方法,是否需要拦截事件

那么这里就分为两种情况了,第一种,首先intercepted为True,也就是ViewGroup进行拦截处理

// 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 {
	...
}

进去方法里看看

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

可以看到,因为方法是根据传进的child的值来进行不同的操作,这里因为传进来的为null,所以执行super.dispatchTouchEvent(event),所以这里其实想ViewGroup要处理自己事件,就调用父类View的dispatchTouchEvent()方法,把自己当做一个View来处理这些事件,所以这里调用了super.dispatchTouchEvent(event),至于View的dispatchTouchEvent()事件怎么处理的,后面会分析到。

第二者,如果intercepted为false,贴出部分代码

final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
    final int childIndex = customOrder
            ? getChildDrawingOrder(childrenCount, i) : i;
    final View child = (preorderedList == null)
            ? children[childIndex] : preorderedList.get(childIndex);

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

代码比较长,主要总结下,遍历ViewGroup的所有元素,如果触摸的事件落在遍历到的view,并且当前遍历到的元素是可以接受到这个事件的,满足这两个条件,这个元素才能接收到父元素传递给他的事件。若两个条件有一个不满足就continue

最终可以看到还是走到了dispatchTouchEvent方法,不过这里回传进去child值,之前也看到过这个方法了,如果child不为空的话,会调用child的dispatchTouchEvent方法,也就是事件从ViewGroup会传递到View中了。

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

View##dispatchTouchEvent

终于到了View中的dispatchTouchEvent,打开方法看看

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

可以看到mOnTouchListener的优先级是高于onTouchEvent的,如果mOnTouchListener不为空,并且复写onTouch方法返回true的话,那么**!result就为false了,此时onTouchEvent(event)就不会执行了,若onTouch返回false,onTouchEvent(event)会执行得到**,这样可以在外部控制处理事件

View##onTouchEvent

if (((viewFlags & CLICKABLE) == CLICKABLE ||
        (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
        (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
    switch (action) {
        case MotionEvent.ACTION_UP:
            boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
            if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
				
				...
                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)) {
                            performClick();
                        }
                    }
                }
				...
            }
			...
            break;
    }
    return true;
}

可以看到,主要走进了这个循环,那么最终是一定返回true的,也就是只要View的CLICKABLE和LONG CLICKABLE有一个位true,那么它就一定会消费这个事件,因为ontouchEvent是返回了true的,然后再ACTION_UP中,会执行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;
    }

是不是恍然大悟,可以看到,如果我们设置的mOnClickListener不为空的话,那么这里会回调onClick方法,也就回调到平常写的onclik方法之中了。

所以事件执行的顺序是DOWN-->MOVE-->UP-->ONCLICK,这里需要注意的一点是,LongClick的执行顺序也是优先于onclick的,如果LongClick的返回位True,也代表着由它消费了这个事件,这个时候onclick也是不会执行的,这个平常在开发的时候需要注意下

好了,大概就是这么多了,有兴趣的朋友可以两篇文章结合的一起看下,希望能够帮助到某些朋友一二吧,谢谢!