Android View变乱分发机制源码分析

手机游戏开发者 2024-9-7 13:39:12 24 0 来自 中国
1.png 简介

不知道什么缘故起因,不知道从什么时间开始,口试八股文是Android开发挥之不去的噩梦,一次又一次的去看去学,然后一样平常开发中容易牵涉不到,导致逢口试就是八股文走一遍,恶心且头秃.
再一次看一下变乱分发的处理处罚,追着源码看一下(有些代码不能Debug,恶心+1)
团体流程

点击屏幕--->WindowCallbackWrapper 吸取到点击-->分发给Activity-->调用PhoneWindow 举行向下转达-->DecorView调用父结构的变乱分发-->ViewGroup dispatchTouchEvent()
然后ViewGroup,View的点击变乱的分发就开始了
关键点类


  • Activity
  • WindowCallbackWrapper
  • PhoneWindow(Window)
  • DecorView
  • ViewGroup
  • View
关键方法


  • dispatchTouchEvent() 变乱分发
  • onTouchEvent() 变乱处理处罚
  • onInterceptTouchEvent() 是否拦截
执行流程

1.WindowCallbackWrapper Activity ,PhoneWindow,DecorView拦截点击变乱

// 窗口回调变乱@RestrictTo(LIBRARY_GROUP_PREFIX)public class WindowCallbackWrapper implements Window.Callback {// Called to process touch screen events.  At the very least your implementation must call//调用以处理处罚触摸屏变乱。至少你的实行必须调用  @Override    public boolean dispatchTouchEvent(MotionEvent event) {        return mWrapped.dispatchTouchEvent(event);    }}//页面ublic class Activity extends ContextThemeWrapper        implements LayoutInflater.Factory2,        Window.Callback, KeyEvent.Callback,        OnCreateContextMenuListener, ComponentCallbacks2,        Window.OnWindowDismissedCallback, WindowControllerCallback,        AutofillManager.AutofillClient {    ....public boolean dispatchTouchEvent(MotionEvent ev) {        if (ev.getAction() == MotionEvent.ACTION_DOWN) {            onUserInteraction();        }        if (getWindow().superDispatchTouchEvent(ev)) {            return true;        }        return onTouchEvent(ev);    }}}// PhoneWindow   Window窗口实现public class PhoneWindow extends Window implements MenuBuilder.Callback {   @Override    public boolean superDispatchTouchEvent(MotionEvent event) {        return mDecor.superDispatchTouchEvent(event);    }}//This is the top-level view of the window, containing the window decor. 页面最顶层控件public class DecorView extends implements RootViewSurfaceTaker, WindowCallbacks {... public boolean superDispatchTouchEvent(MotionEvent event) {//调用到了FrameLayout 的父类ViewGroup        return super.dispatchTouchEvent(event);    }}2. 执行到DecorView的 superDispatchTouchEvent方法就调用到了ViewGroup的dispatchTouchEvent() 方法举行变乱的分发

2.1ViewGroup dispatchTouchEvent() 代码执行
   @Override    public boolean dispatchTouchEvent(MotionEvent ev) {       ....        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. 监测是否拦截变乱(关键点属性)            //判断ViewGroup 是否拦截的变乱            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;            }            // 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;                                    //viewgroup 不拦截点击变乱 ViewGroup 下发变乱            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;                        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.            //假如拦截了上边代码不走 mFirstTouchTarget==null                        if (mFirstTouchTarget == null) {                // No touch targets so treat this as an ordinary view.                //拦截的时间mFirstTouchTarget 是null  调用了    dispatchTransformedTouchEvent()中的  handled = super.dispatchTouchEvent(event);                //意思是回调用父结构的dispatchTouchEvent 的分配也就是View的 dispatchTouchEvent                handled = dispatchTransformedTouchEvent(ev, canceled, null,                        TouchTarget.ALL_POINTER_IDS);            } else {            //假如拦截了 mFirstTouchTarget!=null            // handled 赋值 就竣事了                // 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;                        }                        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;    }2.2 ViewGroup dispatchTransformedTouchEvent()
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,            View child, int desiredPointerIdBits) {          //核心代码就这一个判断          final boolean handled;          if (child == null) {//向上返回//子结构为空调用父结构的变乱分发                       handled = super.dispatchTouchEvent(event);                } else {                //向下执行                //子结构不为空调用子结构的的变乱分发                     handled = child.dispatchTouchEvent(event);                    }        return handled;    }3.View 变乱分发处理处罚

3.1 View dispatchTouchEvent()变乱分发
  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;                        //没有触摸变乱监听 了onTouch()然后返回True 体现消化了            if (li != null && li.mOnTouchListener != null                    && (mViewFlags & ENABLED_MASK) == ENABLED                    && li.mOnTouchListener.onTouch(this, event)) {//直接返回了 消化了变乱                result = true;            }            // 没有触摸变乱监听 继续变乱分发onTouchEvent()消化触摸变乱 onTouchEvent(event)假如返回True 就直接返回True体现消化了触摸变乱 返回false 就向下走返回默认的result            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;    }3.2 View onTouchEvent()是否消化触摸变乱  返回true 体现消化了  返回false 体现不消化 上层结构处理处罚
/**     * Implement this method to handle touch screen motion events.     * <p>     * If this method is used to detect click actions, it is recommended that     * the actions be performed by implementing and calling     * {@link #performClick()}. This will ensure consistent system behavior,     * including:     * <ul>     * <li>obeying click sound preferences     * <li>dispatching OnClickListener calls     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when     * accessibility features are enabled     * </ul>     *     * @param event The motion event.     * @return True if the event was handled, false otherwise.     */    public boolean onTouchEvent(MotionEvent event) {        final float x = event.getX();        final float y = event.getY();        final int viewFlags = mViewFlags;        final int action = event.getAction();                // clickable View 点击变乱的标识 梳理点击变乱和触摸变乱逻辑有效        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) {                    //移除 点击变乱 长按变乱,Button按压的一些状态的回调                         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.                            //处理处罚Button的一些按压状态                            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;        }       默认返回 false  标识不消化触摸变乱        return false;    }总结

简朴的跟着源熟悉了一遍 变乱分发逻辑,大概思绪是 Activity PhoneWindow DecorView 将点击变乱分发到了ViewGroup .ViewGroup 判断本身要不要拦截处理处罚  不拦截处理处罚下发到View  View判断本身是否消化,消化就自身处理处罚 不消化 返回到ViewGroup 处理处罚
末了还有几个点击变乱 和长按变乱 和变乱分发的关系以及逻辑梳理不到位 转头找时间再看看
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 18:28, Processed in 0.171812 second(s), 35 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表