美文网首页Android
Android开发三《View的事件体系》

Android开发三《View的事件体系》

作者: 独自闯天涯的码农 | 来源:发表于2022-03-22 12:28 被阅读0次

    一、View的基础知识

    1、View是界面层的控件的一种抽象,包括ViewGroup
    2、View的位置参数
    VIew的位置主要由四个顶点来决定,对应View的四个属性:top,left,right,bottom
    VIew的坐标系:X轴和Y轴正方向分别为下和右;

    注意:以下参数都是相对于View的父布局坐标
    Left = getLeft() 获取左上角横坐标
    Top = getTop() 获取左上角纵坐标
    Right = getRight() 获取右下角横坐标
    Bottom = getBottom() 获取右下角纵坐标
    x = getX() 获取左上角x坐标
    y= getY() 获取左上角y坐标
    translationX = getTranslationX() 获取左上角相对于父容器偏移量
    translationY = getTranslationY()  获取左上角相对于父容器偏移量
    
    注意:这两个参数是相对于手机屏幕左上角的坐标
    rawX = getRawX() 获取左上角x坐标
    rawY = getRawY() 获取左上角y坐标
    

    View事件相关对象

    1、MotionEvent:
    触摸事件对象,包括坐标
    2、TouchSlop:
    系统所能识别的被认为是滑动的最小距离
    获取方式:ViewConfiguration.get(Context).getScaledTouchSlop();
    3、VelocityTracker:
    速度追踪,用于追踪手指在滑动过程中的速度,包括水平和垂直方向速度,由上往下为正值;
    速度 =(终点位置- 起点位置)/时间
    4、GestureDetoctor:
    手势检测,用于辅助检测用户的单击、滑动、长按、双击等行为;一般使用检测双击;
    5、Scroller:
    弹性滑动对象,用于实现View的弹性滑动.
    

    二、View的滑动

    View滑动方式三种:
    1、使用scrollTo/scrollBy,滑动的是内容

    scroolTo:绝对滑动
    mScrollX = view的边缘- view中内容边缘
    所以从左往右滑动,mScrollX为负值,反之为正值;
    从上往下滑动,mScroolY为负值,反之为正值;
    scroolBy:相对滑动,其内部调用的scrollTo方法
    

    2、平移动画
    translationX,translationY
    3、改变布局参数MarginLayoutParams

    三、View的弹性滑动

    即滑动渐进式滑动,三种方式
    1、使用Scroller
    2、使用动画
    3、使用延时策略

    四、View的事件分发机制

    事件分发机制包括三部分:

    1. 从屏幕到App;
    2. 从App到对应页面;
    3. 页面内具体分发。

    1、事件分发从屏幕到App

    1. 硬件与内核部分
      Linux内核会将硬件产生的触摸事件包装为Event存到/dev/input/event[x]目录下;
    2. SystemServer部分
      在SystemServer进程中管理事件输入的InputManagerService,会启动一个读线程,也就是InputReader,它会从系统也就是/dev/input/目录拿到任务,并且分发给InputDispatcher线程,然后进行统一的事件分发调度。
    3. 跨进程通信传递给App
      我们的App中的Window与InputManagerService之间的通信实际上使用的InputChannel(在ViewRootImpl.setView()过程中,也会同时注册InputChannel);InputChannel是一个pipe,底层实际是通过socket进行通信。最终会走到InputEventReceiver.dispachInputEvent方法。

    2、事件分发从App到对应页面

    1. 事件回传到ViewRootImpl

    InputEventReceiver.dispachInputEvent方法即ViewRootImpl中WindowInputEventReceiver实现了InputEventReceiver接口,最终调用
    ViewRootImpl.enqueueInputEvent方法

    //InputEventReceiver.java
    private void dispatchInputEvent(int seq, InputEvent event) {
        mSeqMap.put(event.getSequenceNumber(), seq);
        onInputEvent(event); 
    }
    
    //ViewRootImpl.java ::WindowInputEventReceiver
    final class WindowInputEventReceiver extends InputEventReceiver {
        public void onInputEvent(InputEvent event) {
           enqueueInputEvent(event, this, 0, true); 
        }
    }
    
    //ViewRootImpl.java
    void enqueueInputEvent(InputEvent event,
            InputEventReceiver receiver, int flags, boolean processImmediately) {
        adjustInputEventForCompatibility(event);
        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
    
        QueuedInputEvent last = mPendingInputEventTail;
        if (last == null) {
            mPendingInputEventHead = q;
            mPendingInputEventTail = q;
        } else {
            last.mNext = q;
            mPendingInputEventTail = q;
        }
        mPendingInputEventCount += 1;
    
        if (processImmediately) {
            //责任链分发
            doProcessInputEvents(); 
        } else {
            scheduleProcessInputEvents();
        }
    }
    
    2. 第一次责任链分发

    调用doProcessInputEvents()方法,涉及到事件分发中的第一次责任链分发(InputStage的责任链ViewRootImpl.setView方法中就已经组装好了)

    不同责任链作用:
    SyntheticInputStage。综合处理事件阶段,比如处理导航面板、操作杆等事件。
    ViewPostImeInputStage。视图输入处理阶段,比如按键、手指触摸等运动事件,我们熟知的view事件分发就发生在这个阶段。
    NativePostImeInputStage。本地方法处理阶段,主要构建了可延迟的队列。
    EarlyPostImeInputStage。输入法早期处理阶段。
    ImeInputStage。输入法事件处理阶段,处理输入法字符。
    ViewPreImeInputStage。视图预处理输入法事件阶段,调用视图view的dispatchKeyEventPreIme方法。
    NativePreImeInputStage。本地方法预处理输入法事件阶段。
    
    3. View触摸事件分发给ViewPostImeInputStage

    最终ViewPostImeInputStage中会调用mView.dispatchPointerEvent方法;(ViewRootImpl中的mView就是DecorView)

    //View.java
        public final boolean dispatchPointerEvent(MotionEvent event) {
                if (event.isTouchEvent()) {
                    return dispatchTouchEvent(event);
                } else {
                    return dispatchGenericMotionEvent(event);
            }
        }
    
    4. 事件在Activity,Window,DecorView中的传递

    最终调用DecorView的dispatchTouchEvent

    //DecorView.java
        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            //cb其实就是对应的Activity/Dialog
            final Window.Callback cb = mWindow.getCallback();
            return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
                    ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
        }
    
    
    //Activity.java
        public boolean dispatchTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                onUserInteraction();
            }
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
            return onTouchEvent(ev);
        }
    
    //PhoneWindow.java
        @Override
        public boolean superDispatchTouchEvent(MotionEvent event) {
            return mDecor.superDispatchTouchEvent(event);
        }
    
    //DecorView.java
        public boolean superDispatchTouchEvent(MotionEvent event) {
            return super.dispatchTouchEvent(event);
        }    
    

    事件分发经过了: ViewRootImpl -> DecorView -> Activity -> PhoneWindow -> DecorView

    3、事件分发页面内部

    1. ViewGroup分发事件
    @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();
                }
    
                //检查是否拦截:只有ActionDown或者mFirstTouchTarget为空时才会判断是否拦截
                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 isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
                final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
                        && !isMouseEvent;
                TouchTarget newTouchTarget = null;
                boolean alreadyDispatchedToNewTouchTarget = false;
                //事件传递给子view
                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 =
                                    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;
                            //遍历子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;
                                }
                                //2.判断事件坐标
                                if (!child.canReceivePointerEvents()
                                        || !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);
                                //3.传递事件
                                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();
                                    //如果子View消耗了则给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;
                        }
                    }
                }
    
                //mFirstTouchTarget不为空时会调用dispatchTransformendTouchEvent
                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;
                            }
                            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;
        }
    
    private boolean dispatchTransformedTouchEvent(View child) {
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else { 
                handled = child.dispatchTouchEvent(event);
            }
        }
    
    1. 只有当Action_Down或者mFirstTouchTarget不为空时才判断是否拦截;
    2. mFirstTouchTarget是个链表结构,代表某个子View消费了事件,为null则表示没有子View消费事件
    3. disallowIntercept字段是用来是否不拦截;由子View调用方法控制;
    getParent().requestDisallowInterceptTouchEvent(true);
    
    1. mFirstTouchTarget==null有两种情况,一是ViewGroup拦截,二是子View没有处理事件,两种情况最后都回调到ViewGroup.onTouchEvent;
    2. dispatchTransformedTouchEvent做的主要就是两个事,如果child不为null,则事件分发到child,否则调用super.dispatchTouchEvent,并最终返回结果
    3. 利用dispatchTransformedTouchEvent,如果返回true,则通过addTouchTarget对mFirstTouchTarget赋值。
    2. 子View分发事件
    public boolean dispatchTouchEvent(MotionEvent event) {
            //如果事件应该首先由可访问性焦点处理。
            if (event.isTargetAccessibilityFocus()) {
                // 我们没有焦点或没有虚拟后代有它,不要处理事件。
                if (!isAccessibilityFocusedViewOrHost()) {
                    return false;
                }
                // 我们有焦点并得到了事件,然后使用正常的事件调度。
                event.setTargetAccessibilityFocus(false);
            }
            boolean result = false;
    
            if (mInputEventConsistencyVerifier != null) {
                mInputEventConsistencyVerifier.onTouchEvent(event, 0);
            }
    
            final int actionMasked = event.getActionMasked();
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // 新手势的防御性清理
                stopNestedScroll();
            }
    
            if (onFilterTouchEventForSecurity(event)) {
                if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                    result = true;
                }
                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;
                }
            }
    
            if (!result && mInputEventConsistencyVerifier != null) {
                mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
            }
    
            // 如果这是手势的结束,则在嵌套滚动后清理;如果我们尝试了 ACTION_DOWN 但我们不想要其余的手势,也可以取消它。
            if (actionMasked == MotionEvent.ACTION_UP ||
                    actionMasked == MotionEvent.ACTION_CANCEL ||
                    (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
                stopNestedScroll();
            }
    
            return result;
        }
    

    子View的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
                    && (mPrivateFlags4 & PFLAG4_ALLOW_CLICK_WHEN_DISABLED) == 0) {
                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) {
                            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.
                                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(
                                    ViewConfiguration.getLongPressTimeout(),
                                    x,
                                    y,
                                    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                            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(
                                    ViewConfiguration.getLongPressTimeout(),
                                    x,
                                    y,
                                    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        }
                        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);
                        }
    
                        final int motionClassification = event.getClassification();
                        final boolean ambiguousGesture =
                                motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
                        int touchSlop = mTouchSlop;
                        if (ambiguousGesture && hasPendingLongPressCallback()) {
                            if (!pointInView(x, y, touchSlop)) {
                                // The default action here is to cancel long press. But instead, we
                                // just extend the timeout here, in case the classification
                                // stays ambiguous.
                                removeLongPressCallback();
                                long delay = (long) (ViewConfiguration.getLongPressTimeout()
                                        * mAmbiguousGestureMultiplier);
                                // Subtract the time already spent
                                delay -= event.getEventTime() - event.getDownTime();
                                checkForLongClick(
                                        delay,
                                        x,
                                        y,
                                        TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                            }
                            touchSlop *= mAmbiguousGestureMultiplier;
                        }
    
                        // Be lenient about moving outside of buttons
                        if (!pointInView(x, y, touchSlop)) {
                            // Outside button
                            // Remove any future long press/tap checks
                            removeTapCallback();
                            removeLongPressCallback();
                            if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                                setPressed(false);
                            }
                            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                        }
    
                        final boolean deepPress =
                                motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
                        if (deepPress && hasPendingLongPressCallback()) {
                            // process the long click action immediately
                            removeLongPressCallback();
                            checkForLongClick(0 ,x,y,
    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
                        }
                        break;
                }
                return true;
            }
            return false;
        }
    
    1. 如果设置了setOnTouchListener并且返回为true,那么onTouchEvent就不再执行
    2. 否则执行onTouchEvent,我们常用的OnClickListenr就是在onTouchEvent里的Up事件中触发的。

    总结:
    1、事件分发的本质就是一个递归方法,通过往下传递,调用dispatchTouchEvent方法,找到事件的处理者,这也就是项目中常见的责任链模式。
    2、在分发过程中,ViewGroup通过onInterceptTouchEvent判断是否拦截事件
    3、在分发过程中,View的默认通过onTouchEvent处理事件
    4、如果底层View不消费,则默认一步步往上执行父元素onTouchEvent方法。
    5、如果所有View的onTouchEvent方法都返回false,则最后会执行到Activity的onTouchEvent方法,事件分发也就结束了。

    参考:
    Android事件分发8连问
    Android事件分发

    五、View的滑动冲突

    解决方法:
    1、外部拦截法
    核心思想:父容器需要的事件拦截,不需要的不拦截;
    重写父容器的onInterceptTouchEvent方法,在内部MotionEvent.ACTION_MOVE事件中做相应拦截;

    /**
     * 拦截事件
     * @param ev
     * @return
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
       boolean intercepted = false;
       int x = (int) ev.getX();
       int y = (int) ev.getY();
    
       switch (ev.getAction()) {
           /*如果拦截了Down事件,则子类不会拿到这个事件序列*/
           case MotionEvent.ACTION_DOWN:
               lastXIntercept = x;
               lastYIntercept = y;
               intercepted = false;
               break;
           case MotionEvent.ACTION_MOVE:
               final int deltaX = x - lastXIntercept;
               final int deltaY = y - lastYIntercept;
                /*根据条件判断是否拦截该事件*/
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    intercepted = true;
                } else {
                    intercepted = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                intercepted = false;
                break;
    
        }
        lastXIntercept = x;
        lastYIntercept = y;
        return intercepted;
    }
    

    2、内部拦截法
    核心思想:父容器不拦截所有事件,子元素需要此事件就消耗掉,否则交给父容器处理;
    重写子View的dispatchTouchEvent方法,在内部MotionEvent.ACTION_DOWN事件中做相应拦截;
    MotionEvent.ACTION_MOVE事件中根据条件取消拦截;

    ViewGroup中onInterceptTouchEvent方法处理

      @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            //内部拦截法
            int action = ev.getAction();
            if (action==MotionEvent.ACTION_DOWN)//down事件不进行拦截
            {
                return false;
            }else {
                return true;
            }
    }
    

    子View中dispatchTouchEvent方法处理

      @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            parent= getParent();
            switch (ev.getAction()){
                case MotionEvent.ACTION_DOWN:
                    parent.requestDisallowInterceptTouchEvent(true);
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (viewgroup需要此事件) //根据实际情况换成你自己的判定条件
                    {
                        parent.requestDisallowInterceptTouchEvent(false);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }
            return super.dispatchTouchEvent(ev);
        }
    
    

    相关文章

      网友评论

        本文标题:Android开发三《View的事件体系》

        本文链接:https://www.haomeiwen.com/subject/bnozlrtx.html