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

上篇对总体事件分发流程大体梳理下,有兴趣的朋友能够去看看事件分发机制(一):解惑篇java

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

Acitvity ## dispatchTouchEvent

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

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都可以打断这个流程。this

PhoneWindow ## superDispatchTouchEvent

惟一实现Window类的就是PhoneWindow类,因此实际上就是调用PhoneWindow的方法了spa

@Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }
复制代码

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

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重置。orm

  • 咱们应该还记得,子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()事件怎么处理的,后面会分析到。ci

第两者,若是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也是不会执行的,这个日常在开发的时候须要注意下

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

相关文章
相关标签/搜索