Android View 触摸反馈原理浅析

重写OnTouchEvent() 然后在方法内部写触摸算法

返回true,表示消费事件,所有触摸反馈不再生效,返回事件所有权

if (event.actionMasked == MotionEvent.ACTION_UP){
    performClick()//抬起事件 执行performClick 触发点击
}
override fun onTouchEvent(event: MotionEvent): Boolean {
  //event 触摸事件
}

//所有的触摸事件都是一个序列,如Down-Up,Down-Up-Cancel,Down-Move

//实例1 

View TouchEvnet ->ViewGroup TouchEvent

//实例2

View1 TouchEvnet ->View2 TouchEvnet ->ViewGroup TouchEvent

 

event.action 和ActionMarked区别

ActionMarked属性:

ACTION_MASK
ACTION_DOWN
ACTION_UP
ACTION_MOVE
ACTION_CANCEL
ACTION_OUTSIDE
ACTION_POINTER_DOWN
ACTION_POINTER_UP
ACTION_HOVER_MOVE
ACTION_SCROLL
ACTION_HOVER_ENTER
ACTION_HOVER_EXIT
ACTION_BUTTON_PRESS
ACTION_BUTTON_RELEASE
ACTION_POINTER_INDEX_MASK
ACTION_POINTER_INDEX_SHIFT

....

ActionMarked相比Action,适用于多点触控 //ACTION_POINTER_UP 非第一根手指抬起

新版会根据事件和Pointer

event.Action会拿到多个事件 如down 可能会action-down - action-pointer-down,会融合多个事件

onTouchEvent

public boolean onTouchEvent(MotionEvent event) {
    final float x = event.getX(); //x坐标
    final float y = event.getY(); //y坐标
    final int viewFlags = mViewFlags;
    final int action = event.getAction(); //Action
    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; //如果可点击但禁用 返回clickable 标记消费
}
if (mTouchDelegate != null) {
    if (mTouchDelegate.onTouchEvent(event)) {
        return true;
        //mTouchDelegate 增加点击区域
    }
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
//TOOLTIP API26以上新特性 解释工具 辅助工具
//可点击或者有辅助工具解释描述
    switch (action) {
        case MotionEvent.ACTION_UP:
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            if ((viewFlags & TOOLTIP) == TOOLTIP) {
                //辅助提示 松开手指消失 1500ms
                handleTooltipUp();
            }
            if (!clickable) {
                //不可点击 取消所有事件
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                break;
            }
        
        boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
        //按下或者预准备按下
        if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
        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); //按下状态为true
            }

    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();
    }
    //延迟操作置空 64ms 自动抬起
    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;
         //是否触摸到View
    }
    mHasPerformedLongPress = false;

    if (!clickable) {
          //不可点击则检查长按 会有延迟执行
        checkForLongClick(
                ViewConfiguration.getLongPressTimeout(), x, y,
                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
        break;
    }

    if (performButtonActionOnTouchDown(event)) {
           //鼠标右键点击 显示上下文菜单
        break;
    }

 
/*
如果在滑动控件 不停递归 返回状态
public boolean isInScrollingContainer() {
    ViewParent p = getParent();
    while (p != null && p instanceof ViewGroup) {
        if (((ViewGroup) p).shouldDelayChildPressedState()) {
//shouldDelayChildPressedState 是否延迟子View延迟状态
            return true;
        }
        p = p.getParent();
    }
    return false;
}
*/
    boolean isInScrollingContainer = isInScrollingContainer();
    //预按下 是否滑动或者按下 进行延迟判断
    if (isInScrollingContainer) {
        mPrivateFlags |= PFLAG_PREPRESSED; 
        if (mPendingCheckForTap == null) {
            mPendingCheckForTap = new CheckForTap();


/*

private final class CheckForTap implements Runnable {
    public float x;
    public float y;

    @Override
    public void run() {
        mPrivateFlags &= ~PFLAG_PREPRESSED; //置空预点击
        setPressed(true, x, y);
        final long delay = //检查长按
                ViewConfiguration.getLongPressTimeout() - ViewConfiguration.getTapTimeout();
        checkForLongClick(delay, x, y, TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
    }
}
*/
        }
        mPendingCheckForTap.x = event.getX();
        mPendingCheckForTap.y = event.getY();
        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout() ); //100ms

    } else {
        // Not inside a scrolling container, so show the feedback right away

        setPressed(true, x, y); //不在滑动控件 设为按下状态
        checkForLongClick( //检查是否要长按,设置等待器
                ViewConfiguration.getLongPressTimeout(), //500ms
                x,
                y,
                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                //预按下 需要等待 getLongPressTimeout 500 -  getTapTimeout 100ms
    }
    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) {
        //可点击 5.0后波纹效果
        drawableHotspotChanged(x, y);
    }

    final int motionClassification = event.getClassification();
    final boolean ambiguousGesture =
        //未规定手势 增加长按事件
            motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
    int touchSlop = mTouchSlop;
    if (ambiguousGesture && hasPendingLongPressCallback()) {
        final float ambiguousMultiplier =
                ViewConfiguration.getAmbiguousGestureMultiplier();
        if (!pointInView(x, y, touchSlop)) {
        //如果手指出界限 ,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();
            // 长按事件的两倍ms
            long delay = (long) (ViewConfiguration.getLongPressTimeout()
                    * ambiguousMultiplier);
            // Subtract the time already spent
              delay -= event.getEventTime() - event.getDownTime();
            //检查长按
            checkForLongClick(
                    delay,
                    x,
                    y,
                    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
        }
        touchSlop *= ambiguousMultiplier;
    }

    // Be lenient about moving outside of buttons
    if (!pointInView(x, y, touchSlop)) {
       //取消事件
        removeTapCallback();
        removeLongPressCallback();
        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
            setPressed(false);
        }
        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
    }

//Android 10 用力点击 触发长按
    final boolean deepPress =
            motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
    if (deepPress && hasPendingLongPressCallback()) {
        // process the long click action immediately
        removeLongPressCallback();
        checkForLongClick(
                0 /* send immediately */,
                x,
                y,
                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
    }

    break;


        }
}

如果不是滑动Layout 可以重写sholdDelayChildPressedState false 关闭延迟点击事件

ViewGroup:

onIntercerceptTouchEvent

onTouchEvent

onIntercerceptTouchEvent 判断是否拦截

1.

ViewGroup onIntercerceptTouchEvent false ->View -> onTouchEvent false ->... ->ViewGroup ->onTouchEvent

2.

ViewGroup onIntercerceptTouchEvent false -> ViewGroup onIntercerceptTouchEvent false -> View -> onTouchEvent false ->... ->ViewGroup ->onTouchEvent  ->ViewGroup ->onTouchEvent

3.

ViewGroup onIntercerceptTouchEven true -> ViewGroup -> onTouchEvent true

 ViewGroup onInterceptTouchEvent 建议先返回false 放行,然后记录 事件/数据做准备

disparchTouchEvent 管理ViewGroup的onIntercerceptTouchEvent  / onTouchEvent

disparchTouchEvent 管理有View的 onTouchEvent

子View dispatchTouchEvent 返回true 消费事件不再传递

ViewGroup dispatchTouchEvent调用super.dispatchTouchEvent

View dispatchTouchEvnet:

  if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            //mOnTouchListener touch事件监听 有则不调用onTouchEvnet
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            if (!result && onTouchEvent(event)) {
                result = true;
            }
return TouchEvent
        }

ViewGroup.dispatchTouchEvent -> 核心

if(intercptTouchEvent)

{onTouchEvent}

else{子View.dispatchTouchEvent}

  @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); //清空状态,确保view没有按下, 是全新的一个序列 down  
                resetTouchState();//拦截子View
            }

            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN // 按下事件判断子View的是否拦截
                    || mFirstTouchTarget != null) {
                //mFirstTouchTarget 有子View被按下
                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;
            //非取消和拦截状态
            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;

                //split 多点触控,
                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 (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            //获取有没有在触摸的子View可以接收
                            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.
                                //pointerIdBits 添加进去
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);

                               //没有在触摸的子View可以接收,尝试能都找到新的子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();
                                //添加
                                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.
            //子View不接收事件
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                //调用自己的TouchEvent
                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; //内部被触摸到的子View
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //处理子View偏移
                        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;
    }







 @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {

//在down之后 和 up之前 ,在父View ViewGroup 调用,同一事件不拦截
        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }

        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }

        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }


dispatchTransformedTouchEvent () ViewGroup 偏移计算 处理子View 进行转换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值