View事件分发源码分析

View的事件分发的基本方法

在View的事件分发过程中主要涉及到dispatchTouchEvent(),onTouch()和onTouchEvent(),onInterceptTouchEvent()。
dispatchTouchEvent()返回值表示是否继续事件分发
onTouch()表示事件是否被消耗
onTouchEvent()中主要处理点击Click事件
onInterceptTouchEvent()中判断是否要拦截某个事件

Touch事件传到Activity的流程

在这里插入图片描述

设备上的Touch首先传递到Activity上,再由Activity的dispatchTouchEvent进行委派

    //Activity——dispatchTouchEvent
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        	//空方法
            onUserInteraction();
        }
        //getWindow()是获取Window的抽象类,而window的唯一实现就PhoneWindow
        //即调用PhoneWindow.superDispatchTouchEvent
        if (getWindow().superDispatchTouchEvent(ev)) {
        	//如果处理了事件返回true结束
            return true;
        }
        //如果事件未被消费,调用Activity的onTouchEvent
        return onTouchEvent(ev);
    }

	//PhoneWindow.superDispatchTouchEvent
	public boolean superDispatchTouchEvent(MotionEvent event) {
        //Decor即是DecorView,是定义在PhoneWindow中的内部类,phoneWindow将事件传递给了DecorView
        return mDecor.superDispatchTouchEvent(event);
       
    }

	//DecorView定义如下 继承自FrameLayout,其实,系统会对任意一个Activity的最外层嵌套一个FrameLayout
	private final class DecorView extends FrameLayout implements RootViewSurfaceTaker{}

	
	//DecorView.superDispatchTouchEvent源码
 	public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
        //调用了FrameLayout(也就是ViewGroupdispatchTouchEvent)
        //事件从Activity传到了ViewGroup
    }

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

        return false;
    }

在这里插入图片描述

ViewGroup的事件分发

ViewGroup中事件的传递流程是dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent
dispatchTouchEvent决定了Touch事件是由自己处理还是分发给子View处理。

ViewGroup——dispatchTouchEvent

 public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
			//第一步:对ACTION_DOWN处理 因为它是一系列事件的开端,在这里进行一些初始化操作
			//清除以往的Touch状态,开始新的手势
			
            // 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.
                //将mFirstTouchTargets设置为null
                cancelAndClearTouchTargets(ev);
                //重置Touch标识
                resetTouchState();
            }

            //第二步: Check for interception. 检查是否要拦截
            // 使用变量intercepted来标记ViewGroup是否拦截Touch事件的传递
            final boolean intercepted;
            //处理ACTION_DOWN事件
            //当ACTION_DOWN事件被子View消费后处理ACTION_MOVE, ACTION_UP时,此时mFirstTouchTarget != null。所以此时ViewGroup是有机会拦截ACTION_MOVE, ACTION_UP的
            //但是我们可以通过调用requestDisallowInterceptTouchEvent来禁止ViewGroup的事件拦截。
            //如果子View没有消耗Touch事件,那么后续的ACTION_MOVE, ACTION_UP事件是不会调用到本处的
            
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //判断是否设置了标志位
                //FLAG_DISALLOW_INTERCEPT设置后,ViewGroup无法栏除ACTION_DOWN之外的其他点击直接。
                //原因:在ViewGroup分发事件时,如果是ACTION_DOWN,会重置这个标志位   
             	//设置方法: requestDisallowInterceptTouchEvent

                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                //当ViewGroup决定拦截事件后,后续的点击事件都会默认交给它处理 不在调用onInterceptTouchEvent
                //当子View处理Touch事件时,mFirstTouchTarget不为空,如果为空则说明事件被ViewGroup处理
                // 只有允许拦截才执行onInterceptTouchEvent方法
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                	//设置不允许拦截,直接设为false
                    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;
            }

            // If intercepted, start normal event dispatch. Also if there is already
            // a view that is handling the gesture, do normal event dispatch.
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            //第三步: Check for cancelation.检查canceled(检查是否取消)
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            final boolean isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
            
            //第四步:事件分发
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
                    && !isMouseEvent;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            //没有取消且不拦截
            if (!canceled && !intercepted) {
                // If the event is targeting accessibility 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.
                //处理ACTION_DOWN
                //总结:对于ACTION_DOWN的处理具体体现在dispatchTransformedTouchEvent
                //true——事件被消费——mFirstTouchTarget!=null
                //false——事件未被消费——mFirstTouchTarget==null
                //因为dispatchTransformedTouchEvent会递归调用dispatchTouchEvent和onTouchEvent 而其返回值主要由onTouchEvent决定
                //简单来说就是onTouchEvent是否消费了Touch事件的返回值决定了dispatchTransformedTouchEvent的返回值,进而决定了mFirstTouchTarget是否为null,ViewGroup是否处理Touch事件
                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;
                    //依据Touch坐标寻找子View来接收Touch事件
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x =
                                isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
                        final float y =
                                isMouseEvent ? ev.getYCursorPosition() : 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 (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
							//找到了接收Touch的子View 即为newTouchTarget
							//跳出循环
                            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);
                            //调用dispatchTransformedTouchEvent将Touch事件传递给子View做递归处理(遍历子View的View树)
                            //该方法内为一个递归调用,会递归调用dispatchTouchEvent方法
                            //dispatchTouchEvent中如果子View为ViewGroup且Touch没有被拦截会递归调用dispatchTouchEvent
                            //如果是View那么就会调用其onTouchEvent
                            //该方法返回true表示子View消费了该事件同时进入if
                            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
                                //该方法涉及到ViewGroup中的内部类——TouchTarget——是一个事件链
                                //该出的mFirstTouchTarget就是一个TouchTarget,它保存了可以消耗Touch的View
                                //如果dispatchTransformedTouchEvent返回true即子View的onTouchEvent返回true则说明View消耗了Touch事件,那么将该View加入到事件链中
                                //根据最外层的if判断可知,当处理ACTION_MOVE,ACTION_UP时不会进入该判断,而是直接判断mFirstTouchTarge
                                //说明了当View不处理ACTION_DOWN后续的事件也不会传递给该View
                                //addTouchTarget将child添加到mFirstTouchTarget链表的头部 该方法内会对mFirstTouchEvent操作,使其不为null
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                //赋值为true 已经将Touch派发给新的TouchTarget
                                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();
                    }
					//没有找到子View接收Touch事件,并且mFirstTouchTarget不为空
                    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;
                        }
                        //指向最初的TouchTarget
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }//处理ACTION_DOWN结束
                }
            }

			//ACTION_DOWN处理结束后mFirstTouchTarget会有两种情况
			//为null :没有找到可以消费的子组件或者是被拦截了
			//不为null 找到了子组件后续的事件都可以传递到子组件
			//这两种情况都会调用dispatchTransformedTouchEvent
			//改方法源码中分析了为什么View处理事件其上层的VieGoup无法处理Touch事件
			//为什么View不处理上层的ViewGroup可以处理Touch事件
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
            	//没有被处理 此时ViewGroup像一个View一样调用dispatchTouchEvent,且在其中调用OnTouchEvent方法
            	//具体实现就是第三个参数View child为null
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
            	//找到了可以消费Touch事件的子View且后续事件都可以传递给子View
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it.  Cancel touch targets if necessary.
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    	//如果前面利用ACTION_DOWN寻找符合接收条件的子View的同时消费掉了ACTION_DOWN事件
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //对于非ACTION_DOWN事件继续传递给目标子组件进行处理
                        //依然是调用dispatchTransformedTouchEvent
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }

            // Update list of touch targets for pointer up or cancel, if needed.
            //处理ACTION_UP和ACTION_CANCEL
            //主要操作时还原状态
            if (canceled
                    || actionMasked == MotionEvent.ACTION_UP
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }

ViewGroup——onInterceptTouchEvent

public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }

在这里插入图片描述

View的事件分发

从dispatchTouchEvent()开始,返回true表示继续事件分发,返回false时终止。
View —— dispatchTouchEvent()中可以看出,该方法的返回值有两种情况。
满足if判断时返回true。
四个if判断

  • 首先判断ListenerInfo对象是否为空
  • mOnTouchListener不等于null
  • 当前控件是ENABLED的
  • 调用li.mOnTouchListener.onTouch(this, event)返回的结果

主要看第四个条件,在onTouch中会处理一系列的ACTION_DOWN, ACTION_MOVE, ACTION_UP。
该onTouch方法返回true表示事件已经消耗。
比如在处理ACTION_DOWN时返回true才会继续分发ACTION_MOVE事件
如果ACTION_DOWN返回false,那么后续的MOVE, UP事件将不会分发。
如果if条件不满足,那么会返回onTouchEvent(event)的执行结果。

以上可以看出onTouch和onTouchEvent的区别和关系

  • 先调用onTouch后调用onTouchEvent
  • 在onTouch中处理了一系列DOWN, MOVE, UP事件,未被消耗才会调用onTouchEvent
  • 在onTouchEvent中的ACTION_UP事件里会调用performClick处理onClick事件
  • Touch事件优先于Click事件发生和处理,且onTouch方法默认返回false。

View —— dispatchTouchEvent核心代码

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

在以下源码中可以看到有四个判断,满足其中的任意一个就会返回true给onTouchEvent方法(可点击的),如果都不满足会返回false

View —— onTouchEvent核心代码

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
		...

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            ...
            return true;
        }

        return false;

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值