Android System——事件传递(二) ViewGroup

上一篇分析了View也就是子控件的事件传递机制,现在我们来看一下父容器也就是ViewGroup的事件传递

ViewGroup事件分发

ViewGroup和普通的view相比,多了一个onInterceptTouchEvent,我们还是通过自定义一个ViewGroup来查看ViewGroup的事件传递

  • MyRelativeLayout.java
/**
 * @author wxblack-mac
 * @DESCRIBE:
 * @DATE 2019/3/28 09:58
 * GOOD LUCK
 */
public class MyRelativeLayout extends RelativeLayout {
    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d(TAG, "onInterceptTouchEvent: event" + ev.getAction());
        return super.onInterceptTouchEvent(ev);
    }
}
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.d9ing.toucheventlsn.MyRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.d9ing.toucheventlsn.MyButton
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BUTTON" />

</com.d9ing.toucheventlsn.MyRelativeLayout>

然后我们执行程序点击MyButton查看事件的执行情况

《Android System——事件传递(二) ViewGroup》 log日志输出

从日志的打印我们可以看出,点击事件先发生在ViewGroup上
我们可以看到ViewGroup的事件响应顺序是:
dispatchTouchEvent—->onInterceptTouchEvent—>onTouchListener—->onTouchEvent

我们看ViewGroup的源码来分析一下我们观察到的流程
在ViewGroup的dispatchTouchEvent方法中,我们看到调用了onInterceptTouchEvent,看onInterceptTouchEvent的返回是true还是false
如果是true表示拦截事件,不会给子View分发事件,会自己消费这个事件
如果是false表示不拦截,会遍历所有的子控件,将事件分发给子控件

 if (!canceled && !intercepted) {

                // If the event is targeting accessibility 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.
...省略一些代码
  // 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;
            }

我们可以看到,在dispatchTouchEvent方法中ViewGroup会遍历子View,然后会调用dispatchTransformedTouchEvent

  for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
.....省略一些代码
 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;
                            }

我们看dispatchTransformedTouchEvent中的方法

  // 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);
        }

结合ViewGroup的源码还有View的源码我们可以知道,如果View的Clickable、longClieckable等设置为false,则handled会返回false dispatchTransformedTouchEvent方法的作用就是判断ViewGroup是否有子控件或者是否有子控件需要消耗事件。
如果ViewGroup如果存在子控件的情况下,如果子控件的child是一个ViewGroup这个时候就会递归执行继续遍历ViewGroup。

就会将事件分发给子View,会执行子View的dispatchTouchEvent方法
如果ViewGroup不存在子View, handled = super.dispatchTouchEvent(transformedEvent);会返回false。dispatchTransformedTouchEvent也会返回false。如果返回false后表示没有要消费事件的View。
然后接下来就会分发事件到真正的触摸对象。

// 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);
            }

这里我们可以看到当mFirstTouchTarget为null的时候表示没有子控件。在dispatchTransformedTouchEvent方法中会调用父类的dispatchTouchEvent。将事件传递会父类或者父容器的dispatchTouchEvent。这样事件就又回到了父类当中。
如果存在子View,ViewGroup会找到真正触摸发生的对象。

  // 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;
                }
            }

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;
                }

从这段代码中我们就能看到 会不断的循环找下一个触摸的目标。需要最终找到消费掉这个事件的对象,没有找到后,也就是代码中的mFirstTouchTarget这个为空的时候,事件就会被自己消费掉。

总结

看了这么多的源码,感觉已经懵逼了。我们来画一张图来总结这个事件传递的过程

《Android System——事件传递(二) ViewGroup》 事件分发源码流程图1.png

这个图并不很完整,只是说明了正常的情况,还有一些情况我们在这解释一下:
上图中,在最后一个子View的onTouch事件中,如果子View返回了true则子View会将事件消费掉。如果onTouch返回false代表子View不消费事件,则事件会传递回父容器的dispatchTouchEvent经过super.dispatch传递到父容器也就是上图第二个容器的onTouch事件。如果父容器的onTouch返回的是true代表事件被父容器消费。如果返回的是false代表父容器不消费这个事件,事件会继续想上传,传给父容器的dispatchTouchEvent,在dispatchTouchEvent内部会传递给父容器的onTouch,如果onTouch返回true代表本事件被消费,返回false表示不消费事件。则事件继续向上传。
所以在调用表示的就是,在子view的onTouch返回false后会传递事件到父容器的onTouch再向上传递到父容器的onTouch。但是实际的事件传递要多了一个传递到dispatchTouchEvent。再由dispatchTouchEvent执行super.dispatchTouchEvent调用onTouch。

    原文作者:So_ProbuING
    原文地址: https://www.jianshu.com/p/4bb8fb078b62
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞