view事件分发源码学习和分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y1962475006/article/details/53385314

activity是承载视图和事件的,所以我们从activity入手。和事件相关的三个方法:dispatchTouchEvent,onInterceptTouchEvent,onTouchEvent。
我们先看activity的dispatchTouchEvent:

/**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

先看一下一下api说明:
调用这个方法来处理屏幕的触摸事件,你可以重写这个方法在所有触摸事件交由window处理之前将它拦截。(这样看来activity的事件是要交给window去处理的)
这个方法先是判断是不是down事件,如果是,执行用户自定义的交互事件,这个onUserInteraction是个空方法,需要自己实现。然后交由当前activity所在window处理。
window类是一个虚类,看一下api的说明:

/**
* Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.
*
*

The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
*/

window类是一个顶级窗口类,包含了显示和行为的处理策略。这个类的实例应该被用来作为添加到window manager的顶级view。它提供了标准UI策略例如背景,标题区域、默认key进程等。这个类提供的唯一实现类是android.view.PhoneWindow。所以我们找到PhoneWindow的superDispatchTouchEvent:

public boolean superDispatchTouchEvent(MotionEvent event) {
            return super.dispatchTouchEvent(event);
        }

跟一下发现,调到了ViewGroup的dispatchTouchEvent。至此,触摸事件由activity--》window--》ViewGroup。


ViewGroup的分发处理:

public boolean dispatchTouchEvent(MotionEvent ev) {                                          
  ….                                                                           
    // 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();
            }
对于down事件,总是会清空FLAG_DISALLOW_INTERCEPT;
        // 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;                                                              
        }                                                                                    

这段代码是对是否已经拦截的判断。可以看出,只要不是down事件,inercepeted都会是true。
如果是down事件或者mFirstTouchTarget不是null,去检查FLAG_DISALLOW_INTERCEPT标识位,如果允许拦截,就会去调用onInterceptTouchEvent,intercepted标识位取onInterceptTouchEvent,如果不允许拦截,intercepted为false,并存储action以防发生改变。intercepted不论从字面意思还是代码上都可以看出,是用来标识是否由当前view group拦截了的。

mFirstTouchTarget是TouchTarget的一个实例,First touch target in the linked list of touch targets. 是touch target 单列表的第一个实例。TouchTarget是用来描述捕获到的可触摸view以及触摸点的id的类。


        // 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);                                           
        }                                                                                    
如果由当前viewGroup拦截,那么开启正常的事件分发;同样的如果已经有处理这个手势的view(有别的view处理了)也正常分发事件。  
        // 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;                              
前面如果由当前viewGroup处理 ev.setTargetAccessibilityFocus(false);这里childWithAccessibilityFocus就会是null,否则就是找到具有处理能力的子view。
            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);                              
移除早先的TouchTargets以防它们已经不是同步的了。
                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 = buildOrderedChildList();          
                    final boolean customOrder = preorderedList == null                       
                            && isChildrenDrawingOrderEnabled();                              
                    final View[] children = mChildren;                                       
                    for (int i = childrenCount - 1; i >= 0; i--) {                           
                        final int childIndex = customOrder                                   
                                ? getChildDrawingOrder(childrenCount, i) : i;                
                        final View child = (preorderedList == null)                          
                                ? children[childIndex] : preorderedList.get(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;                                           
                        }                                                                    
按一定的顺序(从前到后)遍历所有子 view,如果这个子 view 可以接收事件,就把childWithAccessibilityFocus置为null。其实就是过滤找出来这个能接收事件的view。
                        if (!canViewReceivePointerEvents(child)                              
                                || !isTransformedTouchPointInView(x, y, child, null)) {      
                            ev.setTargetAccessibilityFocus(false);                           
                            continue;                                                        
                        }                                                                    
又检查了一遍之前找到的child是否能接受手势事件(跟进去看,是检查child是否可见和child是否有动画存在可见或有动画都返回true)和是不是手指位置在这个子 view child中。不是的话就重新去找,并
ev.setTargetAccessibilityFocus(false);
                        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;                                                           
                        }                                                                    
检查child是否正在接受手势,如果是,跳出遍历。
                        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();                      
                }

dispatchTransformedTouchEvent这个方法跟进去,发现一大堆东西,其实就是说了如果child为空,调用super.dispatchTouchEvent(event),否则调用child.dispatchTouchEvent(event)。明显这里传的child不是null,所以调用的是child.dispatchTouchEvent(event)。如果child.dispatchTouchEvent(event)返回了true,就是说child处理了手势。那么就会alreadyDispatchedToNewTouchTarget设为true;并addTouchTarget,看看里面怎么写的:

/**
 * Adds a touch target for specified child to the beginning of the list.
 * Assumes the target child is not already present.
 */
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
    TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}

可以看到,这里mFirstTouchTarget会被赋值,而且TouchTarget是个单链表结构,mFirstTouchTarget指向了之前找到的child。
继续跟viewGroup的dispatchTouchEvent方法:

                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);  
如果遍历了全部子元素还是没有找到可以处理的,就把自己视作普通view、 并且  dispatchTransformedTouchEvent 传了null, 里面就是调用super.dispatchTouchEvent(event)也就是view的dispatchTouchEvent。                                      
        } 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; 
 如果找到了处理的child,并且处理完了,直接handle设为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;                                                               
            }                                                                                
        }                                                                                    
上面这段是遍历touchTarget 单链表,对每个接收事件的child 进行分发(dispatchTransformedTouchEvent)
        // 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;                                                                          
}                                                       

总结一下viewGroup的分发:
1. down事件都会重置FLAG_DISALLOW_INTERCEPT标识,而FLAG_DISALLOW_INTERCEPT子view可以通过requestDisallowInterceptTouchEvent 设置,来控制viewGroup父类是否执行onInterceptTouchEvent();所以requestDisallowInterceptTouchEvent方法对down事件不起作用。如果requestDisallowInterceptTouchEvent设置为true,那么除了down事件其他事件都不会拦截。所以requestDisallowInterceptTouchEvent应该写在子类的down事件中(此时父类down已经处理了),在move和up到来时起作用。
2. viewGroup父类在down事件一定会去调用onInterceptTouchEvent判断是不是需要拦截。
3. viewGroup父类重写onInterceptTouchEvent,down事件不能返回true,就是说down事件不能被拦截。因为从代码上看,需要在down事件去遍历子元素,找到分发给哪个child处理,如果intercepted为true,都不会走这段代码,导致一直都找不到可以接收事件的子元素。这也是为什么除了down事件其他都直接返回intercepted 为true,因为在move和up事件,mFirstTouchTarget不会为null。并且cancelChild一直都是true,move和up事件通过dispatchTransformedTouchEvent下发。


接下来就是view的分发,因为无论是super.dispatchTouchEvent还是child.dispatchTouchEvent都是调用的view:

/**
     * 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();
        }
如果是down事件,停止折叠滚动
        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
如果view可以点击且有onTouchListener且onTouch方法返回true;result设为trueif (!result && onTouchEvent(event)) {
                result = true;
            }
        }
如果onTouchEvent返回true;result设为trueif (!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();
        }
up、取消或者result为false情况下的down事件都会停止nestScroll。
        return result;
    }

相比viewGroup,view的分发简单一些。可以看到,响应的顺序是onTouchListener--》onTouchEvent。如果在onTouchListener的onTouch方法中返回true,那么这个view的onTouchEvent方法不会调用。

猜你喜欢

转载自blog.csdn.net/y1962475006/article/details/53385314