android事件分发源码解析(下)

一 前言

  上一篇我们介绍了android事件分发的view相关的事件分发源码,我们接着这篇分析一下ViewGroup的相关源码,把事件分发这个机制梳理一次,只有自己认真的分析一次才有收获。

二 例子现象

我们简单写一个例子测试一下:
自定义一个简单的LinearLayout,代码如下:

public class MyLayout extends LinearLayout{
    public MyLayout(Context context) {
        super(context);
    }

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("TAG", "mylayout dispatchTouchEvent" + ev.getAction());
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d("TAG", "mylayout onInterceptTouchEvent" + ev.getAction());
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d("TAG", "mylayout onTouchEvent" + event.getAction());
        return super.onTouchEvent(event);
    }

布局界面如下:

<?xml version="1.0" encoding="utf-8"?>
<com.ww.viewgroupevent.MyLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button"
        android:textSize="16sp"/>
</com.ww.viewgroupevent.MyLayout>
public class MainActivity extends AppCompatActivity {
    private Button btn;
    private MyLayout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        layout = (MyLayout) findViewById(R.id.layout);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("TAG", "button click");
            }
        });
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("TAG", "layout click");
            }
        });
    }

}

上面布局都很简单,运行界面如下所示:
这里写图片描述

我们点击button,log日志如下所示:
这里写图片描述

我们可以看到点击button先执行的是ViewGroup的dispatchTouchEvent,即LinearLayout的dispatchTouchEvent,而且比view多了一个方法,onInterceptTouchEvent,最后执行的是Button的点击事件,那么我们可以看到执行的一个顺序是父布局开始,dispatchTouchEvent->onInterceptTouchEvent->向子view传递。

当我们点击空白区域的时候,log日志如下所示:
这里写图片描述

这里跟上面有点不一样的地方,就是在action0,即按下的时候,执行的是dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent,而action1的时候就没有执行onInterceptTouchEvent,这里是一个疑问,先记住,源码里面找到答案。可以发现,其实跟view的分发还是有很多不一样的。

三 ViewGroup的事件分发

  1. ViewGroup的事件分发过程
    android执行点击事件,一般是从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 = 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;
                            }
    
                            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;
    }    

    我们看到这里源码很长,我们只分析主要的:
    8-10行:这里主要判断是否是针对可访问视图焦点,这个东西呢主要是帮助残障人士的,一般我们手机的设置里面就有一个无障碍功能,就是跟这个有关系,主要是通过AccessibilityService服务运行在后台的,感兴趣的可以查看这篇文章看看:
    Android进阶——学习AccessibilityService实现微信抢红包插件

    18-24行:我们执行按下操作的时候,首先执行了ACTION_DOWN ,一般来说执行第一步的都是初始化各种值,我们可以看到17-24行首先清除以前Touch的状态,开始一个新的手势,然后在cancelAndClearTouchTargets(ev) 这个方法里面对mFirstTouchTarget 设置为null了,这个是一个很关键的一个地方,对分析后面的事件分发比较重要,接着在resetTouchState() 里面清楚Touch的状态。

    27-41行:VIewGroup会在两种情况下判断是否要拦截当前事件,通过事件类型ACTION_DOWNmFirstTouchTarget != null,其实前面按下事件很好理解,主要是后面这个TouchTarget 的对象mFirstTouchTarget != null 这个是关键,当找到目标view接收Touch事件的时候,那么这个对象就会被赋值并指向子元素,进入里面接着判断disallowIntercept,这个也在ViewGroup也提供了相应的设置方法:

    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    
        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }
    
        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }
    
        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }

    这里就是通过改变mGroupFlags的值来确定是否拦截,当你调用这个方法的时候,disallowIntercept为true的时候,将这个FLAG_DISALLOW_INTERCEPT 标记位添加到mGroupFlags里面,当设置为false的时候,就清除mGroupFlags中的FLAG_DISALLOW_INTERCEPT。所以在disallowIntercept为true的时候前面判断了mGroupFlags是否包含了这个标记位,如果包含了,说明这个状态已经存在,就不必在添加了。当设置后,那么disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; 这条语句就为true,那么intercepted = false;就默认不拦截事件,交由子元素处理;如果没设置这个拦截标志呢,按照正常的分发,首先调用onInterceptTouchEvent(ev); 将它赋值给intercepted,我们看看这个方法:

    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

    没错,默认返回为false,我们如果不重写这个方法的话,不会拦截事件分发的。
    如果没找到目标view接收Touch事件或者找到了接收的目标view但是没有处理,上述28-29行的if语句不成立,直接将intercepted = true,并且onInterceptTouchEvent(ev) 事件将不会调用,那么后续到来的事件都会交给它来处理。 上面那个疑问也就解释了,自己处理就不会调用拦截事件了。

    总结一下:
    事件传递总是先传递给父View的,然后才有父元素分发给子View,可以通过requestDisallowInterceptTouchEvent 方法在子元素中干预父元素的事件分发,但是ACTION_DOWN除外,因为每一次都要通过resetTouchState(); 这个方法里面的mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 清除这个标记位。

    50-51行检查事件是否被取消。

    54行还是通过标记位检查事件是否支持分发多个view,默认是true,也提供了设置方法,跟上面设置拦截标记的类似,一个套路。

    57行if (!canceled && !intercepted)判断了是否取消和拦截。 如果没有取消和拦截,则进入if里面。

    67-69行是一大串if语句,里面判断了是不是按下,第二个条件则是一个点被按下,此时在按下其它点触发,第三个条件就是鼠标在view上面。下面开始处理ACTION_DOWN事件。

    79行判断childrenCount是否为0,首先获取触摸位置。84行拿到了子view的集合preorderedList,然后通过倒序遍历所有子View,一般布局或者addview的话,后添加的肯定在上面,这也比较符合思维方式,如果点击的地方有两个view的话,如果两个view都可以点击,那么肯定是最上层的先响应。
    判断子元素是否能够接收到点击事件,主要由两点来判断,子元素是否在播放动画和点击事件是否落在子元素的区域内。

    98-104:还是判断视图是否是一个可访问性焦点,我们首先让它获取事件,不处理就正常分发,虽然会分发两次,但是可以保证在给定的时间内更安全的执行。还是一开始提到的方便使用有关系,其它地方也有这个判断。

    106-110行:检查view是否允许接收事件,是否处于visible状态或者正在播放动画和点击事件的坐标是否落在子元素的范围内。

    112-118行:getTouchTarget这个判断了当前子view是否包含在了mFirstTouchTarget.next这个链表的某一个 target中,找到了就返回这个target,没找到就返回null。接着if判断找到了这个target就进入内部,childView已经准备接收在其区域内的点击事件,并且执行break跳出for循环。
    如果没有跳出的话就执行121-140行,这里首先通过dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign) 将touch事件传递给子view,这个方法内部会递归调用dispatchTouchEvent(event) 方法,这个方法后面讲解,需要明白的一点是,这个方法返回true,那么就表示消费了这个事件,就进入这个if内部。

    123-136行,从这几个变量的注释看,仅供debug调式用。

    137-139行,给newTouchTarget赋值,设置alreadyDispatchedToNewTouchTarget 为true,然后执行break跳出for循环,因为已经找到了View接收Touch事件。其实mFirstTouchTarget的赋值过程 是在addTouchTarget 内部完成的,代码如下:

    private TouchTarget addTouchTarget(View child, int pointerIdBits) {
        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

    mFirstTouchTarget 是一种单链表的结构,是否赋值将直接影响到ViewGroup对事件的拦截,如果为null的话,默认拦截接下来的同一序列中所有的点击事件,比如ACTION_MOVE,ACTION_UP。

    149-157行:if (newTouchTarget == null && mFirstTouchTarget != null) 这个if语句就是没有找到子View接收Touch事件,并且之前的mFirstTouchTarget 不为null,那么将newTouchTarget指向了最初的TouchTarget。

    162-196行:这里经过上面的分析,主要就是两种情况,第一种情况就是mFirstTouchTarget==null ,没有找到能消费Touch事件的view或者被View拦截了。那么在ViewGroup的dispatchTransformedTouchEvent 方法里面处理Touch事件和普通的View一样,自己无法消费,传递给上一层进行处理。这里调用dispatchTransformedTouchEvent 方法时第三个参数为null,下面会讲解这个方法,先记住就行。

    第二种情况就是找到了能消费Touch事件的view,那么后续的同一序列事件,都应该交由它处理。

    173-175行:前面利用ACTION_DOWN事件找到了符合接收touch事件的子view同时消费掉了ACTION_DOWN事件,这里直接返回true。

    176-192行:对于非ACTION_DOWN事件,继续传递给目标view进行处理,依然是递归调用dispatchTransformedTouchEvent 方法处理。如果ACTION_DOWN 没有被拦截,但是同一序列的其它事件被拦截,则需要发送ACTION_CANCLE给目标view。

    199行-203行:如果是ACTION_UP或者ACTION_HOVER_MOVE,那么将重置Touch状态标识,mFirstTouchTarget = null。

    ViewGroup的dispatchTouchEvent事件分析完了,我们看到在上述分析的时候
    dispatchTransformedTouchEvent这个方法执行了多次,我们接下来看看这个方法,源码如下:

    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;
    
        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }
    
        // Calculate the number of pointers to deliver.
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
    
        // If for some reason we ended up in an inconsistent state where it looks like we
        // might produce a motion event with no pointers in it, then drop the event.
        if (newPointerIdBits == 0) {
            return false;
        }
    
        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
        final MotionEvent transformedEvent;
        if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);
    
                    handled = child.dispatchTouchEvent(event);
    
                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }
    
        // Perform any necessary transformations and dispatch.
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }
    
            handled = child.dispatchTouchEvent(transformedEvent);
        }
    
        // Done.
        transformedEvent.recycle();
        return handled;
    }

    这里我们可以看到对事件具体的处理,代码比较多,我们分析关键点。
    我们应当重点关注第三个参数,因为上面再调用的时候,一会儿为null,一会儿不为null,这里就给出了解释,重点是这段代码:

    if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }

    我们可以看到,在child为null的时候,Touch事件会传递给viewGroup自身的dispatchTouchEvent处理,即父类view的方法,在里面处理ontouch,上一篇已经分析过了,就不在多讲。当child不为null的时候,那么会调用childview的dispatchTouchEvent 处理,childView可能是一个view也可能是一个viewGroup。
    这个方法里面后面讲的就是一些多点触控的相关处理,就不在赘述。

四 总结

  1. Android事件分发是先传递到ViewGroup,再由ViewGroup传递到View的,一层一层向下传递。
  2. 在ViewGroup中可以通过onInterceptTouchEvent方法对事件传递进行拦截,onInterceptTouchEvent方法返回true代表不允许事件继续向子View传递,返回false代表不对事件进行拦截,默认返回false。
  3. 子View中如果将传递的事件消费掉,ViewGroup中将无法接收到任何事件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值