思考几个问题:
1. recycleview嵌套recycleview 双向滑动如何解决滑动冲突问题?
2. 自定义viewgroup如何指定内部view的事件响应顺序?
3. view和viewgroup的在事件处理上有和区别?
4. 事件分发对象有哪几类?
5. onTouch()和onTouchEvent()哪个优先级高?
6. 事件在哪些对象之间进行传递?
阅读建议:
网上对于Android源码讲解文章很多,有代码+注释的,有的还带图解的,但是如果自己不跟着源码读一遍,那么只会在别人的理解之上去理解,但是好多博文并不会很详细的去解释每个点或者博主没时间只分享主干线的一些点,那么读者对内部的实现还是不会有深入的理解,所以要想有深入的全面的理解还得自己花时间去解读,其实源码里面好多的算法 数据结构都和相似,设计方式也差不多,所以多读几遍也就对其他的源码不陌生了。
Anroid事件分发机制
不管是学习android开发还是面试,事件分发机制一般都会讲到或被问到,网上搜索更是一坨坨的博客文章,基本都是雷同或者就是抄袭的。有的写得比较不错,也对源码的流程线路做了分析,但是一些细节还是没有能够说清楚,但是对于理解android的事件分发和开发app已经够用了。
Android事件从Activity开始有外到内传递,依次Activity->Window->View这么传递,这是比较粗粒度的划分;再细致分为Activity->ViewGroup->View,然后通过onTouchEvent方法进行事件处理。那么页面很复杂,点击屏幕的事件会被哪个View最终消费呢?为什么是所有在这个点的view都能响应呢?这就是面试常问事件分发机制的原因,因为在一些负责的UI显示效果需要对点击事件有深入的认识,处理好事件的分发才能处理好UI的交互,比如经常会问recycleView嵌套滑动的问题。
事件分发机制重点讲ViewGroup和View内部的实现,因为最终事件分发和消费就是在这两个级别的View对象中被处理。网上一般都会说到三个与事件处理相关的方法:
- dispatchTouchEvent()
- onTouchEvent()
- onInterceptTouchEvent()
那么还是先来说说Activity的事件分发流程:
当点击屏幕时焦点会先到Activity中,至于是怎么到Activity中的这里先不用去管,但猜想一下肯定和硬件驱动有关系,肯定是底层驱动通过binder将事件传递到上层的windowManager,然后在activity的,这里只是猜想具体的需要去看源码。
Acivity# dispatchTouchEvent调用了window#superDispatchTouchEvent方法,然后肯定和DecorView有关系了,而DecorView是继承于ViewGroup的,所以就到了ViewGroup的业务范围了。
ViewGroup的事件分发:
首先ViewGroup是View的子类,ViewGroup对dispatchTouchEvent重写了,并且没有直接调用父类的dispatchTouchEvent方法。那就先看看ViewGroup的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) { 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 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();//注释:这里对子view进行排序,如果没有自定义的排序规则则默认就是当前的顺序 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);//注释:如果重新排序了则以排序后的顺序遍历子view,如果没有重新排序则以默认的顺序遍历子view
// 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); 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) { // 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; } |
主要看源码中标黄色底的关键代码:
mFirstTouchTarget:当前ViewGroup中第一个点击到view对象;在addTouchTarget中会对该变量赋值,addTouchTarget具体调用地方看源码;
resetCancelNextUpFlag():对参数View对象的mPrivateFlags移除PFLAG_CANCEL_NEXT_UP_EVENT的位值,通过对PFLAG_CANCEL_NEXT_UP_EVENT“&”操作,判断当前flag中是否包含PFLAG_CANCEL_NEXT_UP_EVENT的位值(如果包含该flag则&操作肯定不为0);
FLAG_XXX:FLAG开头的各种状态;
MotionEvent:事件对象具体的可以参考https://www.jianshu.com/p/0c863bbde8eb写的比较详细这里就不再浪费篇幅,里面主要对触摸点一级action_down、action_move以及action_up的事件处理做了介绍;
findChildWithAccessibilityFocus():通过RootViewImpl找到获得焦点的View,然后判断该View是否是当前ViewGroup的子view,如果是则返回;
removePointersFromTouchTargets():会将该触摸点的之前加到mFirstTouchTarget链表中的View对象清除,有可能之前的动作没有响应新的点击事件又开始。
buildTouchDispatchChildList():根据z坐标和自定义绘图顺序对视图中的view排序。如果ViewGroup的子类对getChildDrawingOrder重写,这顺序会再根据该函数返回的顺序排序。
getAndVerifyPreorderedIndex():获取子view的顺序索引,如果没有重写排序则使用默认排序;
getAndVerifyPreorderedView():通过view的索引获取view,顺序同上。
dispatchTransformedTouchEvent():这里便开始向子view分发事件。如果child为null,则执行父类的dispatchTouchEvent方法。
View的dispatchTouchEvent处理:
/** * Pass the touch screen motion event down to the target view, or this * view if it is the target. * * @param event The motion event to be dispatched. * @return True if the event was handled by the view, false otherwise. */ 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)) { if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { result = true; } //noinspection SimplifiableIfStatement 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); }
// 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;
|
在view的dispatchTouchEvent方法中就调用了onTouchEvent事件,但是如果用户重写了onTouch方法则优先级高于onTouchEvent事件。
总结:
上面主要对一些细节点作了介绍,那么看上去有点乱,这里对事件分发具体的流程进行描述(主要对ViewGroup和View这两层):
- 从Activity到ViewGroup的dispatchTouchEvent中,先判断当前的页面是否没有被遮挡(View#onFilterTouchEventForSecurity);
- 如果第一步校验通过继续判断MotionEvent是否是Action_DOWN类型,如果是则判断是否对子View进行事件拦截。如果拦截则执行ViewGroup父类View的dispatchTouchEvent方法,则最后会执行到ViewGroup的onTouchEvent方法中;如果没有拦截则继续遍历子View并分发事件;
- 给子View分发事件则涉及到顺序的问题,所以在遍历之前会对当前ViewGroup的子view进行排序,然后遍历所有的子view,直到遇到获取到focus的view时调用view的dispatchTouchEvent(通过对比idBitsToAssign是否相等判断是否是focus的View对象),如果view消费了该事件则返回true;否则返回false,那么会继续执行ViewGoup的super.dispatchTouchEvent方法。