事件分发
入口点为Activity中的dispatchTouchEvent(MotionEvent ev)
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
//这个window我们知道是PhoneWindow,那就直接去PhoneWindow吧
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//默认返回时false
return onTouchEvent(ev);
}
PhoneWindow
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
//调用了decorView的这个方法,我们知道,它一定开始要去View中开始搞事情了。
//最后调用了ViewGroup的dispatchTouchEvent(MotionEvent event)
return mDecor.superDispatchTouchEvent(event);
}
ViewGroup
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
//处理down事件
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
//因为是down事件,作为一次新事件的开头,清除上次的标志、缓存
cancelAndClearTouchTargets(ev);
resetTouchState();
}
//检测事件拦截
// Check for interception.
final boolean intercepted;
//Down事件发生的时候 mFirstTouchTarget == null
// Up和Move的时候,mFirstTouchTarget如果在down时找到了消费的那个,mFirstTouchTarget!=null
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//是否不允许拦截?
//默认MGroupFlags值是0 ,disallowIntercept为false ,表示允许拦截
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;
}
########## down判断完之后下面的这个if有点长
//非拦截也非取消信号
if (!canceled && !intercepted) {
//下面为ACTION_DOWN的处理
##### ActionDown才会执行的,找目标~~~
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
//更具view.getZ()的值,来创建这个View集合
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);
// canReceivePointerEvents检测了当前这个View的可见性是否是Visible
// isTransformedTouchPointInView检测了位置是否在该区域
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);
//当前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;
//已经找到一个,并且返回了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();
}
//上面如果找到了一个View并且在返回了true,那么这里不会执行
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) { //没有找到孩子来搞事情 // 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) { //up时重置mFirstTouchTarget等 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); } //返回handled,标致结束 return handled;}
ACTION DOWN的时候,主要是要找到目标View(即位置在范围内,并且可见性为Visible的),而且它的目标是找到一个消费事件的View,加入进mFirstTouchTarget这个链表,这样,当下次事件:Move、Up事件来到的时候,就直接从mFirstTouchTaget取出这个目标View,直接调用dispatchTransformedTouchEvent进行事件分发。也就是一个View,如果在Down事件发生的时候,返回了false,不处理,那么后续的Move和Up事件都不会接收到。
dispatchTransformedTouchEvent
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
handled = child.dispatchTouchEvent(transformedEvent);
return handled;
}
火速进入View的dispatchTouchEvent
public boolean dispatchTouchEvent(MotionEvent event) {
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
//如果是ActionDown那么停下滚动
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
// 调用了onTouch()
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//如果该View有设置onTouch事件,那么onTouchEvent就不会被回调是这样的吗?我们试试就知道
###确实是这样的,设置了onTouch那么onTouchEvent就不会被调用了
if (!result && onTouchEvent(event)) {
result = true;
}
}
}
onTouchEvent()
switch (action) {
case MotionEvent.ACTION_UP:
if (prepressed) {
//抬起时设置动画效果
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();
}
//使用Handler发消息的方式触发onClick,而非直接调用,相当于就是留一些时间
if (!post(mPerformClick)) {
performClickInternal();
}
}
上面就在Up事件里面主要调用了onclick的回调(使用Handler进行),同时还有Down事件,主要时判断有没有监听长按事件,如果有,发送一个延时的消息,看了下默认时500ms,根据配置来获得。
事件拦截问题:
- 几个方法:
- dispatchTouchEvent() View和ViewGroup共有
- onInterceptTouchEvent() ViewGroup特有
- requestDisallowInterceptTouchEvent() 用于子View 这个方法名的意思: 不拦截!!不拦截!!记住
down事件很重要,是否能找到可以分发的子View,完全是在Down事件中进行查找,如果当前ViewGroup的包含的View都返回false,那么mFistTouchTarget为空,游戏结束。后续传来的Move和Up都不会收到。该次事件分发给ViewGroup的onTouchEvent处理。如果有子View的Down返回的是true,那么mFirstTouchTarget指向该View,游戏继续进行,后续Move和Up进入:是否有请求不拦截,
没有例子的学习都是耍流氓,ok
//继承LinearLayout
<com.yp.deepstudy.MyLinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:gravity="center"
android:orientation="vertical">
//继承自View
<com.yp.deepstudy.MyView
android:layout_width="120dp"
android:layout_height="120dp"
android:background="@color/colorAccent" />
</com.yp.deepstudy.MyLinearLayout>
-
按下抬起、按下移动抬起,因为down事件都返回的是false,没人处理,所以后续Move和Up都接收不到
// 0代表 down事件 MyLinearLayout: dispatchTouchEvent0 MyLinearLayout: onInterceptTouchEvent0 MyView: dispatchTouchEvent0 MyView: onTouchEvent0 MyLinearLayout: onTouchEvent0
-
现在将MyView,的dispatchTouchEvent改成返回true:下面的log表明有控件进行消费(Down中返回true,如果在move中返回true,也是然并卵的),那么后续事件就将会收到。
MyLinearLayout: dispatchTouchEvent0 MyLinearLayout: onInterceptTouchEvent0 MyView: dispatchTouchEvent0 MyLinearLayout: dispatchTouchEvent2 MyLinearLayout: onInterceptTouchEvent2 MyView: dispatchTouchEvent2 MyLinearLayout: dispatchTouchEvent1 MyLinearLayout: onInterceptTouchEvent1 MyView: dispatchTouchEvent1
下一步开始拦截
-
onInterceptTouchEvent中Action_Move的时候返回true
MyLinearLayout: dispatchTouchEvent_ACTION_DOWN MyLinearLayout: onInterceptTouchEvent_ACTION_DOWN MyView: dispatchTouchEvent_ACTION_DOWN MyView: onTouchEvent_ACTION_DOWN MyLinearLayout: dispatchTouchEvent_ACTION_MOVE MyLinearLayout: onInterceptTouchEvent_ACTION_MOVE MyLinearLayout: 开始拦截 //注意下面MyView中收到的事件是:Cancel MyView: dispatchTouchEvent_ACTION_CANCEL MyView: onTouchEvent_ACTION_CANCEL MyLinearLayout: dispatchTouchEvent_ACTION_MOVE MyLinearLayout: onTouchEvent_ACTION_MOVE MyLinearLayout: dispatchTouchEvent_ACTION_MOVE MyLinearLayout: onTouchEvent_ACTION_MOVE MyLinearLayout: dispatchTouchEvent_ACTION_UP MyLinearLayout: onTouchEvent_ACTION_UP //对上面的log进行代码分析 final boolean cancelChild = resetCancelNextUpFlag(target.child) || intercepted; //intercepted为true if (dispatchTransformedTouchEvent(ev, cancelChild, target.child, target.pointerIdBits)) { handled = true;} //注意上面第二个参数,因为拦截了,传来是true dispatchTransformedTouchEvent final int oldAction = event.getAction(); //cancel为true if (cancel || oldAction == MotionEvent.ACTION_CANCEL) { //在这设置了为Cancel,所以父类拦截,子View收到的事件的Cancel, //当连续的下一次事件进入,mFirstTouchTarget为空,又不是down事件,因此,onInterceptTouchEvent根本不会执行,直接执行父类的dispatchTouchEvent,分发给onTouchEvent event.setAction(MotionEvent.ACTION_CANCEL); if (child == null) { handled = super.dispatchTouchEvent(event); } else { //孩子收到cancel事件 handled = child.dispatchTouchEvent(event); } event.setAction(oldAction); return handled; }
-
注意,一旦父类onInteceptTouchEvent就是完全进行了,不能在这个事件流中分发给子View了。
俗话说的好, 任何不配图的分析都是耍流氓因此: