当前位置:首页 > 编程笔记 > 正文
已解决

Android View 触摸反馈原理浅析

来自网友在路上 156856提问 提问时间:2023-11-07 06:15:30阅读次数: 56

最佳答案 问答题库568位专家为你答疑解惑

重写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(); //Actionfinal 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) {//辅助提示 松开手指消失 1500mshandleTooltipUp();}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 checkremoveLongPressCallback(); //移除长按操作// Only perform take click actions if we were in the pressed stateif (!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 nowmUnsetPressedState.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;@Overridepublic 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 awaysetPressed(true, x, y); //不在滑动控件 设为按下状态checkForLongClick( //检查是否要长按,设置等待器ViewConfiguration.getLongPressTimeout(), //500msx,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();// 长按事件的两倍mslong delay = (long) (ViewConfiguration.getLongPressTimeout()* ambiguousMultiplier);// Subtract the time already spentdelay -= event.getEventTime() - event.getDownTime();//检查长按checkForLongClick(delay,x,y,TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);}touchSlop *= ambiguousMultiplier;}// Be lenient about moving outside of buttonsif (!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 immediatelyremoveLongPressCallback();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 SimplifiableIfStatementListenerInfo li = mListenerInfo;//mOnTouchListener touch事件监听 有则不调用onTouchEvnetif (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}

  @Overridepublic 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 downfinal 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 indexfor (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.//调用自己的TouchEventhandled = 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; //内部被触摸到的子Viewwhile (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;}@Overridepublic 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 tooreturn;}if (disallowIntercept) {mGroupFlags |= FLAG_DISALLOW_INTERCEPT;} else {mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;}// Pass it up to our parentif (mParent != null) {mParent.requestDisallowInterceptTouchEvent(disallowIntercept);}}dispatchTransformedTouchEvent () ViewGroup 偏移计算 处理子View 进行转换

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Android View 触摸反馈原理浅析":http://eshow365.cn/6-34296-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!