安卓View的事件分发机制

一.概述

1.事件的分发概述

View对事件的分发即系统把MotionEvent事件传递给一个具体的View的过程。
这其中涉及三个重要方法:dispatchTouchEvent,onInterceptTouchEvent和onTouchEvent。

2.三个重要方法

三个重要方法

3.基本传递过程

当一个点击事件产生后,一般顺序为先传递到Activity,在传到ViewGroup(这之前会传递到window),最终传到View。

二.事件分发的源码分析

1.Activity对事件的分发

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();	//这是个空方法
        }
        if (getWindow().superDispatchTouchEvent(ev)) { //此处调用了Window类的抽象方法
            return true;
        }
        return onTouchEvent(ev);
    }

因为Window是抽象类,因此我们寻找它的实现类PhoneWindow,找到相应的superDispatchTouchEvent方法。

    public boolean superDispatchTouchEvent(MotionEvent event) {

        //Decor即是DecorView类,所以Window将事件传递给了DecorView
        return mDecor.superDispatchTouchEvent(event);
    }

再进入Decor的superDispatchTouchEvent方法,如下:

    public boolean superDispatchTouchEvent(MotionEvent event) {
    //因为Decor是FrameLayout的子类,FrameLayout是ViewGroup的子类,而FrameLayout中没有相应方法,因此下面一句代码调用了ViewGroup中的方法
    //至此,事件就从Activity传递到了ViewGroup
        return super.dispatchTouchEvent(event);
    }

2.ViewGroup对事件的分发

ViewGroup对事件的分发可以用下面的伪代码表示:

public boolen dispatchTouchEvent(){
	boolen consume = falseif(onInterceptTouchEvent){  
		consume = onTouchEvent(ev); //拦截事件,则调用当前viewGroup的onTouchEvent
	}else{
		consume = child.dispatchTouchEvent(); //否则,调用子view的dispatchTouchEvent,即事件传递给子view
	}
	return consume;
}

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;

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

            // Check for interception.
            final boolean intercepted;	//用来判断是否拦截事件
            //mFirstTouchTarget :当有子元素成功处理事件后,mFirstTouchTarget会被赋值并指向子元素。
            //mFirstTouchTarget!=null 即表示ViewGroup表示未拦截当前事件
            if (actionMasked == MotionEvent.ACTION_DOWN	//事件为“按下”
                    || mFirstTouchTarget != null) {
            //下面的disallowIntercept的值可由FLAG_DISALLOW_INTERCEPT更改
            //更改方法:子View调用requestDisallowInterceptTouchEvent方法
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {	//允许ViewGroup拦截事件
                    intercepted = onInterceptTouchEvent(ev);	//此方法中默认不拦截事件
                    ev.setAction(action); // restore action in case it was changed
                } else {	//不允许拦截事件
                    intercepted = false;
                }
            } else {	//ViewGroup已经拦截过事件,则继续拦截事件
                // 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.
            //如果拦截,则正常分发事件。另外,如果已经有一个View正在处理事件,则执行正常事件分发。
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            // 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 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.
                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;
                        //此处开始对子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;
                            }
						//子View不能收到事件或Touch的坐标不在其范围内,直接跳到下一个子View
                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
							//获取child对应的Touch Target
                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                // Child is already receiving touch within its bounds.		child在它的范围内已经获取了touch事件
                                // Give it the new pointer in addition to the ones it is handling.	除了它正在处理的那个,将新的指针赋给它
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
               				//在dispatchTransformedTouchEvent方法内部,如果child不为null,就会调用child的dispatchTouchEvent方法
               				//至此,事件就传递给了下一层View
                            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();
                                // 如果处理掉了事件,将此child添加到touch链的头部
                                //在addTouchTarget方法中更新了mFirstTouchTarget的值
                                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;
                    }
                }
            }
			// 非down事件直接从这里开始处理,不会走上面的一大堆寻找TouchTarget的逻辑
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
            //没有child处理事件,因此ViewGroup自己进行处理
                // 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.
                //下面的代码作用是将事件分发给touch target。如果已经分发,则不分发给新的touch target。如果必要,则取消touch targets
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                //target是一个链表,下面开始遍历
                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;
                        }
                        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.		如果需要,更新touch targets的链表
            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;
    }

3.View对事件的分发

    public boolean dispatchTouchEvent(MotionEvent event) {
        boolean result = false;
		...
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            //下面判断了该View是否设置了OnTouchListener 
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
			//如果该View设置OnTouchListener事件 ,则onTouchEvent就不会被调用,因此OnTouchListener比onTouchEvent优先级高
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
		...
        return result;
    }

下面逐步View的onTouchEvent方法中的代码:

        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) {
        //由下面的代码可见,不可点击的View仍然会消耗点击事件,尽管它不会对事件进行反应。
            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;
        }

下面是onTouchEvent对事件的具体处理:

//clickable表明该View可以点击(CLICKABLE,LONG_CLICKABLE为true),它为true时
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
		...
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            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方法,现在先调用下面的performClickInternal方法,
                                //是为了通知autofill manager,然后再在其中调用了performClick方法
                                    performClickInternal();
                                }
                            }
                        }
                    	...
                    }
                 break;
            }
    //clickable为true时都会返回true,表示消耗此事件
    return true;
}

三.小结

事件从Activity经ViewGroup到View的传递过程可用如下图表示,黄框表示事件从此处传递给了下一级。
在这里插入图片描述

四.参考资料

《安卓开发艺术探索》
Android之View篇2————View的事件分发
Android事件分发机制详解:史上最全面、最易懂

发布了14 篇原创文章 · 获赞 4 · 访问量 688

猜你喜欢

转载自blog.csdn.net/qq_43935080/article/details/103375483
今日推荐