View的事件分发

2021-04-26  本文已影响0人  撸码的皮大叔

1.View的事件分发

View的事件分发主要涉及到三个方:dispatchTouchEvent、onTouchEvent、onInterceptTouchEvent

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

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

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

三者关系

public boolean dispatchTouchEvent(MotionoEvent ev){
         boolean consume=false;
     if( onInterceptTouchEvent(ev)){
          consume=onTouchEvent(ev);
    }else{
          consume=child. dispatchTouchEvent(ev)
    }

      return consume;
}

传递规则:对于ViewGroup来说,点击事件后 ->dispatchTouchEvent()-> onInterceptTouchEvent()->child.dispatchTouchEvent,如此反复直到事件被最终处,如果onInterceptTouchEvent返回ture,则dispatchTouchEvent()-> onInterceptTouchEvent()->onTouchEvent();

对于一个View需要处理事件,如果设置了OnTouchListener,那么onTouchListener中的onTouch方法会被调用,如果返回false,则onTouchEvent会调用,如果返回ture 则不会调用,
首先进到dispatchTouchEvent方法

 public boolean dispatchTouchEvent(MotionEvent event) {
     
...
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;

          // 当设置了OnTouchListener.onTouch为true 是这个方法能进去 result=true
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
           // 上面result =ture 所用这个onTouchEvent方法就调用不到了,所以这不会走这个方法,
         //onTouchEvent 点击事件是这里面调用的往后看,
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
        return result;
    }

当OnTouchListener.onTouch返回true时,会走到onTouchEvent方法

    public boolean onTouchEvent(MotionEvent event) {
       
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                 
         
                            if (!focusTaken) {
                                // 点击事件
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }

                    
            return true;
        }

        return false;
    }
  private boolean performClickInternal() {
        // Must notify autofill manager before performing the click actions to avoid scenarios where
        // the app has a click listener that changes the state of views the autofill service might
        // be interested on.
        notifyAutofillManagerOnClick();

        return performClick();
    }

//返回result 
 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;
    }

得出一个结论:View的OnTouchListener优先级高于onTouchEent高于OnClickListener,

3.ViewGroup事件分发

ViewGroup比View相对而言复杂些

传递过程遵循如下顺序:Activity ->Window ->View 但事件没有消费最终也是传递给Activity 处理。
事件传递过程是由外到内,及事件总是先传递给父元素,然后在分发子view,通过
requestDisallowInterceptTouchEvent方法可以在子元素中干预父元素的事件分发过程(ViewPager 源码中就有这句话),但是ACTION_DOWN事件除外

2.源码分析

先看Activity 是怎么传递给window然后在传给view

   public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
     // 当没有消费事件,则调用自己的onTouchEvent
        return onTouchEvent(ev);
    }

getWindow().superDispatchTouchEvent(ev) 是调去了window的dispatchTouchEvent, getWindow返回一个Window 抽象类,具体实现是PhoneWindow.class

    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
     // mDecor 是DecorView, 
        return mDecor.superDispatchTouchEvent(event);
    }

//DecorView 每个布局的跟布局,其实setContentView设置的View 是它的一个子View
   @Override
    public final @NonNull View getDecorView() {
        if (mDecor == null || mForceDecorInstall) {
            installDecor();
        }
        return mDecor;
    }

由于DecorView继承FrameLayout且是父View,而FrameLayout 是基础ViewGroup,
接下来直接看ViewGroup,调用则是ViewGroup.dispatchTouchEven()方法,

  @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
     
           
            final boolean intercepted;
   // mFirstTouchTarg当事件由ViewGroup 子元素成功处理时赋值,
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
//FLAG_DISALLOW_INTERCEPT 是子View调用了requestDisallowInterceptTouchEvent来设置的
                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;
            }     
   

    }

上文又说到为什么ACTION_DOWN事件除外?

   // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // Throw away all previous state when starting a new touch gesture.
                // The framework may have dropped the up or cancel event for the previous gesture
                // due to an app switch, ANR, or some other state change.
                cancelAndClearTouchTargets(ev);
                resetTouchState();//
            }
//重置了所以值
   private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }

当ViewGroup 不拦截事件,事件向下分发

 TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) {
                
           
                            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;
                            }

                            // The accessibility focus didn't handle the event, so clear
                            // the flag and do a normal dispatch to all children.
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        // Did not find a child to receive the event.
                        // Assign the pointer to the least recently added target.
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

通过遍历ViewGroup的所有方法,然后调用dispatchTransformedTouchEvent 看这个方法 实际上是调用了子View.dispathTouchEvent()

    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

        final int oldAction = event.getAction();
        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;
        }
        return handled;
    }

如果子元素的dispathTouchEvent返回true,这时,那么mFirstTouchTarget就会被赋值跳出循环

  newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;

mFirstTouchTarget是一个单链表结构,如果mFirstTouchTarget=null 那么ViewGroup就默认拦截接下来同一序列中所用的点击事件

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

如果dispathTouchEvent返回false,那么ViewGroup就会把事件分发给下一个子元素(如果还有下一个子元素)

上一篇下一篇

猜你喜欢

热点阅读