Android 事件分发机制

1、基础
  1. 事件分发对象:点击事件(Touch 事件)。
  2. 事件定义:触摸屏幕,将产生点击事件。Touch 事件的细节(触摸时间、位置等)被封装成 MotionEvent 对象。
  3. 事件类型:
事件类型具体动作
MotionEvent.ACTION_DOWN按下
MotionEvent.ACTION_UP抬起
MotionEvent.ACTION_MOVE滑动
MotionEvent.ACTION_CANCEL取消事件(非人为原因)
  1. 事件类:触摸屏幕至离开屏幕,产生的一系列事件。
    在这里插入图片描述
  2. 事件分发本质:将事件(MotionEvent)传递给某个 View 处理的过程。
  3. 事件分发顺序:Activity->ViewGroup->View。
  4. 事件分发主要方法
方法作用
dispatchTouchEvent()分发事件
onTouchEvent()处理点击事件
onInterceptTouchEvent()拦截事件(ViewGroup 独有)
2、源码分析
  1. Activity 事件分发机制
    在这里插入图片描述
	Activity.java
	
    public boolean dispatchTouchEvent(MotionEvent ev) {
    	// DOWN 事件 
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction(); // -> 分析 1
        }
        // getWindow().superDispatchTouchEvent(ev) 返回 true,方法结束,否则执行 onTouchEvent(ev)。-> 分析 2
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);-> 分析 4
    }
    
	// 分析 1:onUserInteraction()
	// 作用:实现屏保功能
	// activity 在栈顶时,触发 home,back,menu 事件等会触发该方法。
    public void onUserInteraction() {
    }
	
	// 分析 4:onTouchEvent(ev)
	// 当一个事件未被 activity 下任意 view 接收处理。
	// 点击事件在Window边界外才会返回true,默认都返回 false。
    public boolean onTouchEvent(MotionEvent event) {
    	// ->分析 5
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }
	PhoneWindow.java
	
	// 分析 2:getWindow().superDispatchTouchEvent(ev)
	// getWindow() 为  Window 对象。指向唯一实现类 PhoneWindow 对象。
    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);// ->分析 3
    }
	DecorView.java
	
	// 分析 3:mDecor.superDispatchTouchEvent(event)
	// mDecor 为 DecorView(顶级view)
	// DecorView 继承 FrameLayout,FrameLayout 继承 ViewGroup。
	// 将事件传递给 ViewGroup 处理,Activity->ViewGroup。
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }
	Window.java

	// 分析 5:mWindow.shouldCloseOnTouch(this, event)
	// 判断事件在边界外
    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;
    }
  1. ViewGroup 事件分发机制
    在这里插入图片描述
	ViewGroup.java
	
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
     		。。。
            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                 // 1、disallowIntercept 是否禁用拦截,默认 false 不禁用,可以通过 requestDisallowInterceptTouchEvent(boolean disallowIntercept) 修改。
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                	// 2、disallowIntercept 为 false没禁用拦截,调用onInterceptTouchEvent(ev) 拦截事件。
                    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;
            }
			。。。
            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) {

                // If the event is targeting accessiiblity 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.
                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;
                    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;
                        // 3、遍历子view,找到被点击的view。
                        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();
                    }

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

            // Dispatch to touch targets.
            //  4、事件分发到子view。->分析 1
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // 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) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
						。。。
            }
		。。。
        return handled;
    }
	
	// 拦截事件
    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;
    }

	// 分析1:dispatchTransformedTouchEvent
	// 无子view接收事件 或者 拦截事件执行 super.dispatchTouchEvent(transformedEvent)->View.dispatchTouchEvent()->onTouch()->onTouchEvent()->performClick()->onClick()。
	// 否则事件分发到子view(child.dispatchTouchEvent(transformedEvent)):ViewGroup->View
    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
       。。。
        // Perform any necessary transformations and dispatch.
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }
    
  1. View 事件分发机制
    在这里插入图片描述
    public boolean dispatchTouchEvent(MotionEvent event) {
      	。。。
            // 1、mOnTouchListener != null;2、(mViewFlags & ENABLED_MASK) == ENABLED;3、mOnTouchListener.onTouch(this, event))。result = true 及 dispatchTouchEvent 返回true;否则执行onTouchEvent()。
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
			// onTouchEvent(event) ->分析 1
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
		。。。
        return result;
    }

	// 分析 1 :onTouchEvent()
    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;
            }
        }
		// 1、view 可点击
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
            	// 抬起事件
                case MotionEvent.ACTION_UP:
                   			。。。
                   			// 执行performClick()->分析 1
                            performClick();
                            。。。
                    break;
                // 按下事件
                case MotionEvent.ACTION_DOWN:
               		 。。。
                    break;
				// 事件取消
                case MotionEvent.ACTION_CANCEL:
            		。。。
                    break;
				 // 滑动事件
                case MotionEvent.ACTION_MOVE:
             		。。。
                    break;
            }
            // 控件可点击,返回 true。
            return true;
        }
 		// 控件不可点击,返回 false。
        return false;
    }
	
	// 分析 1:performClick()
	// 控件注册点击事件执行 onClick(),返回 true。
	// 没注册点击事件,返回 false。
    public boolean performClick() {
        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;
        }
		。。。
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值