Android 事件分发机制源码解析及总结

版权声明:本文为博主原创文章,转载请注明出处!谢谢! https://blog.csdn.net/aaa1050070637/article/details/89020881

对于Android 事件分发机制呢,其实就是一句话,将点击事件(MotionEvent)分发到具体的View上。

MotionEvent的类型呢,就三种,

  • ACTION_DOWN:手指刚接触屏幕
  • ACTION_MOVE:手指在屏幕上滑动
  • ACTION_UP:手指从屏幕上松开的一瞬间

三个核心的方法:

  • dispatchTouchEvent() 用于事件的分发
  • onInterceptTouchEvent()用于拦截点击事件
  • onTouchEvent() 是否消耗当前事件

事件分发的流程呢,一般是按照Activity--->Window---->ViewGroup这个过程进行传递,现在来看看具体的事件分发源码

Activity的事件分发机制

   public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //用户自己处理
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            //交给Window处理,如果window消耗返回true,代表事件已经被消费掉
            return true;
        }
        //如果返回false,则传递给onTouchEvent
        return onTouchEvent(ev);
    }

接下来看看getWindow().superDispatchTouchEvent(ev),方法,可以看看流程

Window的抽象方法 
public abstract boolean superDispatchTouchEvent(MotionEvent event);
 
PhoneWindow实现
 @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        //交给DecorView处理
        return mDecor.superDispatchTouchEvent(event);
    }

传递给DocerView进行处理
  public boolean superDispatchTouchEvent(MotionEvent event) {
        //交给上级容器ViewGroup处理
        return super.dispatchTouchEvent(event);
    }
最后传递给ViewGroup,进行处理

看到这里,就已经分发到ViewGroup进行处理了。此时我们来看看Activity 中DispatchTouchEvent中的返回值

onTouchEvent(ev)

  public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }

调用Window的shouldCloseOnTouch方法
    /** @hide */
    public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
        final boolean isOutside =
                event.getAction() == MotionEvent.ACTION_DOWN && isOutOfBounds(context, event)
                || event.getAction() == MotionEvent.ACTION_OUTSIDE;
        //
        if (mCloseOnTouchOutside && peekDecorView() != null && isOutside) {
            return true;
        }
        return false;
    }

shouldCloseOnTouch方法呢,主要是判断是否消耗事件,返回True,则事件分发结束,如果返回false,则给ViewGroup进行分发,直到事件被消费掉。

ViewGroup的事件分发机制

我们从上面的流程中来看,没有看到onInterceptTouchEvent方法调用呢,不急,我们接着看

接下来我们看看ViewGroup中的dispatchTouchEvent方法,先看前面一段

扫描二维码关注公众号,回复: 6071748 查看本文章
 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    //截取部分代码
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            
            // Check for interception.
            //检查是否被拦截
            final boolean intercepted;

            if (actionMasked == MotionEvent.ACTION_DOWN
                    //touch事件链表中第一个目标
                    //private TouchTarget mFirstTouchTarget;
                    || mFirstTouchTarget != null) {

                //When set, this ViewGroup should not intercept touch events.
                // ViewGroup不会拦截事件
                //protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000;
                //内部标志 ,它对SDK是隐藏的。
                //protected int mGroupFlags;
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

                //如果不允许拦截的标志位false,即拦截事件
                if (!disallowIntercept) {
                    //Implement this method to intercept all touch screen motion events.
                    //拦截所以touch事件
                    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.
                //没有touch事件,则拦截
                intercepted = true;
            }
}

从文中注释可以看出,onInterceptTouchEvent方法终于登场了,这里可以看到:如果事件被子View消耗 或者 是ACTION_DOWN事件,那就访问该ViewGroup的onInterceptTouchEvent()方法,如果不那就全部被当前ViewGroup拦截。

这就代表,如果ViewGroup决定拦截某个事件,接下来的一系列事件,都由这个view来处理

我们继续往下面看

  // 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();
            }

每次收到Action_Down事件,都会回到初始状态

咱们继续往下面看,如果ViewGroup不拦截事件,他就会将事件传递给子View


                    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;
                            }

                            // 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();
                    }

这一段代码,就是ViewGroup事件分发的主要代码了。

当ViewGroup存在子View的时候,就需要对viewGroup进行遍历了。咱们可以看到这样一个方法,这里也只截取了部分代码

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

        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
        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;
        }

如果子View为null那就交给该ViewGroup的dispatchTouchEvent(),反之就将点击事件交给该子View(也有可能是ViewGroup)处理,一次分发就完成了。 

如果dispatchTransformedTouchEvent()返回true,表明点击事件被子View消耗,执行addTouchTarget()方法给最开始的mFirstTouchTarget赋值

如果遍历完了所有的子View,点击事件都没有被消耗掉,可能有两种情况:

一、ViewGroup下面没有子View。

二、子View没有消耗点击事件。

这两种情况下,ViewGroup会自己处理点击事件。当子View不消耗点击事件,那点击事件将交由给他的父View去处理。

再来看一段代码

  // 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);
            } 

这里child=null;结合上面的代码,就能看出来,此时需要调用View的dispatchTouchEvent方法了。

分析到这里,一个事件分发机制源码流程就算理清楚了。

View的事件分发机制

public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

        boolean result = false;

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }

        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;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

这一段代码比较简单,其中onFilterTouchEventForSecurity(event)方法

  public boolean onFilterTouchEventForSecurity(MotionEvent event) {
        //noinspection RedundantIfStatement
        //如果返回true,则代表调度事件,否则为舍弃事件
        //窗口被遮挡,就舍弃触摸事件
        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
                //此标志表示接收此运动事件的窗口被其上的另一个可见窗口部分或全部遮挡。
                //  public static final int FLAG_WINDOW_IS_OBSCURED = 0x1;
                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
            // Window is obscured, drop this touch.
            return false;
        }
        return true;
    }

用来判断点击事件来到时,窗口有没有被遮挡住,如果被遮挡住则直接返回false,不消耗事件。

这就是我们平时在一个button上面进行点击,不会调用Activity方法的onTouchEvent方法的原因。

最后看看onTouchEvent(MotionEvent )方法,整个流程就算结束了

 public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        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.
            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)) {
                                    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;

                case MotionEvent.ACTION_DOWN:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(0, x, y);
                        break;
                    }

                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(0, x, y);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        drawableHotspotChanged(x, y);
                    }

                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        // Remove any future long press/tap checks
                        removeTapCallback();
                        removeLongPressCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            setPressed(false);
                        }
                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    }
                    break;
            }

            return true;
        }

        return false;
    }

如果View设置了OnClickListener,performClick()这个方法就会去执行这个监听事件。
OnTouchListener的优先级高于OnClickListener,OnClickListener是在ACTION_UP的时候执行的。

源码分析结束了,总结一下,其实用一段伪代码就能说明白

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

最后总结一下三个结论:

1.Android事件分发,按照Activity--->Window--->ViewGroup方向传递

2.如果某个view拦截了一个事件,那么接下来的一系列事件均由这个view来处理

3.onTouchListener优先级高于onClickListener

再来一个干货,分享的一个大牛的图

猜你喜欢

转载自blog.csdn.net/aaa1050070637/article/details/89020881
今日推荐