先看下图,平时简单的也就down,move和up拉。如果多点触控还point down,point up
如下代码,如果我们要禁止掉多点触控
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
println("dispatchTouchEvent==============${MotionEventCompat.getActionMasked(ev)}===${(ev.action )}==${ev.action and MotionEvent.ACTION_MASK}")
if((ev.action and MotionEvent.ACTION_MASK)==MotionEvent.ACTION_POINTER_DOWN){
return true
}
return super.dispatchTouchEvent(ev)
}
一些常用的十六进制和二进制的关系以及作用
0x0100 对应的二进制1 0000 0000
0x0200 对应的二进制10 0000 0000
0x0300 对应的二进制11 0000 0000
0xff00对应的二进制 1111 1111 0000 0000 //这个与操作的话低八位就没了,只保留高八位,然后一般会进行位移操作
0x00ff对应的二进制1111 1111
public static final int ACTION_MASK = 0xff;
public static final int ACTION_POINTER_INDEX_MASK = 0xff00;
然后看这个与操作 ev.action and MotionEvent.ACTION_MASK
因为0xff 转换为二进制就是低八位全是1,所以和它进行操作的结果就是保留低八位,高八位就都成0了
然后看些过时的一些参数
ACTION_POINTER_DOWN =5
public static final int ACTION_POINTER_2_DOWN = ACTION_POINTER_DOWN | 0x0100;
十六进制的2个0就有八位了,也就是低八位是0,和down进行与操作的结果,就是高八位是1,低八位是5
public static final int ACTION_POINTER_3_DOWN = ACTION_POINTER_DOWN | 0x0200;
十六进制的2个0就有八位了,也就是低八位是0,和down进行与操作的结果,就是高八位是2,低八位是5
其实上边的1和2就是索引了,也就是第几根手指触摸屏幕的。
如果我们不关心这个,我们只关系它是不是多点触控,那么就可以与CTION_MASK = 0xff进行与操作,去掉高八位,那么就只保留低八位的,也就是ACTION_POINTER_DOWN 了。
如果你要获取索引是第几根手指,那么结果与ACTION_POINTER_INDEX_MASK = 0xff00进行与操作,就会去掉低八位,然后右移八位,把低八位都去掉,高八位就成低八位了
public static final int ACTION_POINTER_ID_SHIFT = 8;
也就是index=(mAction & ACTION_POINTER_INDEX_MASK) >> ACTION_POINTER_INDEX_SHIFT
index返回就是0,1,2的数字拉。
总结一下
获取普通 的action,比如down,move和up,point down,point up
用如下的方法,会去掉高八位的信息
(ev.action and MotionEvent.ACTION_MASK)
如果要获取高八位的索引,用如下的方法
var index=(ev.action and MotionEvent.ACTION_POINTER_INDEX_MASK) shr MotionEvent.ACTION_POINTER_INDEX_SHIFT//右移8位,获取index
另外进制转换这里有图,忘了可以看下
https://jingyan.baidu.com/article/597a0643614568312b5243c0.html
View的触摸事件
下边注释写了3种返回true的情况
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)) {
//返回true情况1,鼠标在滚动条上拖动
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
//返回true情况2,view调用了setOnTouchListener,并且listener返回为true
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//返回true情况3,view自身的onTouchEvent方法返回true
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;
}
ViewGroup的触摸事件
有如下三个方法
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
val intercept=super.onInterceptTouchEvent(ev)
println("onInterceptTouchEvent==============${ev.action}====$intercept")
return true
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
val result=super.dispatchTouchEvent(ev)
return result
}
override fun onTouchEvent(event: MotionEvent): Boolean {
println("onTouchEvent==============${event.action}")
return super.onTouchEvent(event)
}
一个ViewGroup能否处理触摸事件,或者如果想截断触摸事件,关键就是看dispatchTouchEvent在event等于ACTION_DOWN的时候是否返回true
而其他2个方法都是在super.dispatchTouchEvent(ev)里调用的,如果没有执行这个super方法,那么其他2个方法是不会执行的。
简单研究下dispatchTouchEvent源码
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();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {//不允许中断为false的条件下
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) {//viewgroup自身没有中断触摸事件。
// If the event is targeting accessiiblity 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);
//将event传递给child,看child是否处理,如果处理的话,最后一行alreadyDispatchedToNewTouchTarget =true
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.
if (mFirstTouchTarget == null) {//没有子child处理,那自己处理
// 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(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits)
if (child == null) {
//没有子类处理的时候child为null,这时候调用super方法,其实也就是view的默认dipatchTouchEvent方法拉,这个方法里会调用onTouch方法,上边View分析了
handled = super.dispatchTouchEvent(transformedEvent);
}
//如果child不为空,那么就child处理,然后就一层一层的往下边去拉。
handled = child.dispatchTouchEvent(transformedEvent);