Android高级UI之View事件分发机制与事件冲突的原因及解决

onTouch与onClick之间会产生事件冲突吗?
事件在控件中时如何传递的?
事件冲突的根本原因?
如何解决事件冲突?

MotionEvent

Android高级UI之View事件分发机制与事件冲突的原因及解决_第1张图片

View继承关系

Android高级UI之View事件分发机制与事件冲突的原因及解决_第2张图片
Android高级UI之View事件分发机制与事件冲突的原因及解决_第3张图片

ViewGroup,先要走分发事件流程,再走处理事件流程

View,只能走处理事件流程

Android高级UI之View事件分发机制与事件冲突的原因及解决_第4张图片

onTouch与onClick之间会产生事件冲突吗?

//View.java

 /**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
     
       
       ...
       
            //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;
            }

		...

	}

View的dispatchTouchEvent方法先执行mOnTouchListener的onTouch()方法,只有onTouch()方法返回false时,才去执行onTouchEvent()方法,onClick()方法是在onTouchEvent()方法中调用的。
所以只要onTouch()方法返回true,则onClick()方法是不会执行的。

ViewGroup的dispatchTouchEvent()

//ViewGroup.java


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

			// 步骤1:检查是否要拦截事件,注意是在ACTION_DOWN事件进行判断的
            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
     //如果是ACTION_DOWN事件或者已经有targets要消费该事件,则进行判断是否要拦截事件
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
     //只有disallowIntercept为false,才会调用onInterceptTouchEvent()判断是否拦截
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
     
                    intercepted = false;
                }
            } else {
      // 如果不是ACTION_DOWN事件,并且也没有targets要消费该事件,则ViewGroup进行拦截,自己处理该事件
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                intercepted = true;
            }

			// 如果要拦截该事件,则下面的步骤2是不会执行的,直接执行步骤3进行事件分发
            // 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.
            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;
            //步骤2:如果不拦截事件,则进行寻找targets来消费该事件
            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;

				//只有对DOWN事件才会分发,MOVE和UP事件不会分发
                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;//ViewGroup的直接子View的数量
                    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();//对直接子View按照Z轴进行排序
                        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;
                            }

							//判断这个child是否能接收事件,并且点击事件在child范围里面
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
     
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
								
							//走到这里,说明这个child能接收事件,并且点击事件在child范围里面

                            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()方法将事件分发给child,dispatchTransformedTouchEvent()返回true表示child处理了该事件
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
     
                            	// 进入到这里表示child处理了该事件
                                // 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();
                                //调用addTouchTarget()为该child创建一个新的TouchTarget插入到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;
                    }
                }
            }

			//步骤3:事件分发流程(normal event dispatch),进行事件的分发和处理。拦截或者不拦截事件都会走到这里
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
     //两种情况会走到这里:1.如果自己不拦截事件但是没子View领取事件, 2.或者自己要拦截该事件
            	
                // child参数传null,表示自己处理该事件
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
      //如果自己不拦截事件并且子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) {
     //while循环解决多点触控
                    final TouchTarget next = target.next;
                     //DOWN事件分发会走这里
                    //如果alreadyDispatchedToNewTouchTarget=true并且target == newTouchTarget表示上面child已经处理过了                   
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
     
                        handled = true;
                    } else {
     
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                         //MOVE事件分发会走这里       
                        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.
            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自己处理了事件,要么child递归进行上述分析的dispatchTouchEvent()流程
	 * 
     * Transforms a motion event into the coordinate space of a particular child view,
     * filters out irrelevant pointer ids, and overrides its action if necessary.
     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
     */
    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);//分发一个cancel事件给child
            }
            event.setAction(oldAction);
            return handled;
        }

        // Calculate the number of pointers to deliver.
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

        // If for some reason we ended up in an inconsistent state where it looks like we
        // might produce a motion event with no pointers in it, then drop the event.
        if (newPointerIdBits == 0) {
     
            return false;
        }

        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
        final MotionEvent transformedEvent;
        if (newPointerIdBits == oldPointerIdBits) {
     
            if (child == null || child.hasIdentityMatrix()) {
     
                if (child == null) {
     
                    handled = super.dispatchTouchEvent(event);
                } else {
     
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
     
            transformedEvent = event.split(newPointerIdBits);
        }

        // Perform any necessary transformations and dispatch.
        if (child == null) {
     //如果child==null,则调用super.dispatchTouchEvent()进行处理事件,即调用View的dispatchTouchEvent()
            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;
    }

    /**
     * Adds a touch target for specified child to the beginning of the list.
     * Assumes the target child is not already present.
     */
    private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
     
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

    /**
     * 判断一个View能否接收事件,满足两个条件中的一个:
     * 1.View是VISIBLE的
     * 2.如果View不是VISIBLE,但是有动画
     * 
     * Returns true if a child view can receive pointer events.
     * @hide
     */
    private static boolean canViewReceivePointerEvents(@NonNull View child) {
     
        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                || child.getAnimation() != null;
    }


    /**
     * 判断点击事件是否在child里面
     * 
     * Returns true if a child view contains the specified point when transformed
     * into its coordinate space.
     * Child must not be null.
     * @hide
     */
    protected boolean isTransformedTouchPointInView(float x, float y, View child,
            PointF outLocalPoint) {
     
        final float[] point = getTempPoint();
        point[0] = x;
        point[1] = y;
        transformPointToViewLocal(point, child);
        final boolean isInView = child.pointInView(point[0], point[1]);
        if (isInView && outLocalPoint != null) {
     
            outLocalPoint.set(point[0], point[1]);
        }
        return isInView;
    }

总结

一、
ViewGroup,先要走分发事件流程,如果没人处理事件,就再走处理事件流程
View,只能走处理事件流程

二、
分发流程:
DOWN–确定事件给谁
1.先判断是否拦截后自己处理事件(即不分发下去)
2.如果不拦截,则分发下去:
排序
遍历分发
领取事件的子View 处理事件
3.如果没子View领取或者自己要拦截该事件,再看下自己是否要处理该事件,进行事件分发处理流程
(如果自己要拦截该事件,则相当于自己是最后一个View,要判断自己是否要处理该事件
)

MOVE–处理事件
1.先看是否拦截后自己处理事件(即不分发下去),子View可以请求不拦截
2.分发下去:
直接由down事件确定的view进行事件处理

拦截MOVE事件—只能在MOVE事件中处理事件冲突
如果之前已经将事件分发给了子View,但是后来父容器拦截了MOVE事件,则
第一个MOVE事件的作用:给子View发送一个cancel事件,并且将mFirstTouchTarget置为null(对于单点触摸事件),这时候父容器是没有处理这个MOVE事件的。

第二个MOVE事件到来时,父容器才处理事件。

三、
对于叶节点,如果没有拿到DOWN事件,则也就拿不到MOVE和UP事件;但是对于非叶节点,如果没有拿到DOWN事件,也可以拿到MOVE和UP事件。

四、
对于ACTION_MOVE和ACTION_UP事件,因为mFirstTouchTarget != null,所以也会调用onInterceptTouchEvent()判断是否要拦截:


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
     
			
		...
			
            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
     
                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事件才会从直接子View中寻找TouchTarget,寻找到新的TouchTarget时会更新mFirstTouchTarget,所以只要找到TouchTarget那么mFirstTouchTarget就!=null,如果没有从子View中找到TouchTarget或者自己拦截了事件,则TouchTarget==null。ACTION_MOVE事件不会寻找TouchTarget。

六、
当子View作为TouchTarget,但是后面的MOVE事件父容器进行了拦截,则第一个MOVE事件会转为CANCEL事件分发给TouchTarget。

七、
子View一旦拿到DOWN事件,后面的事件由谁处理是由子View决定的。

八、
父布局可以拦截子布局的事件,但是子布局不能拦截父布局的事件。

你可能感兴趣的:(Android面试题,Android,JAVA)