您的位置:首页 > 移动开发 > Android开发

关于Android 中View的分发机制的学习与总结(ViewGroup篇)

2017-02-23 15:46 489 查看
这是我自己参考了网上许多关于View 的分发机制的文章之后的总结,可能有错误,也有解释的不对的地方,请指正。我尽量做到不打错别字,不造成阅读障碍。

说明:源码已变,但是结构思想未变,仍具有参考价值,你也可以找低的API版本。

从Activity开始

 首先,每个做得页面应该大多数控件都是在一个LinearLayout或其他布局内部的,而整个布局又会setContentView到Activity中,所以先从Activity干的事开始讲解。

Activity在绘制完整个界面后——才有可能监听你的点击事件,Activity中有一个dispatchTouchEvent方法,这个方法会处理其中ViewGroup的点击事件,看代码

public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {

            onUserInteraction();

        }

        if (getWindow().superDispatchTouchEvent(ev)) {

            return true;

        }

        return onTouchEvent(ev);

    }

事件到达Activity时,会调用Activity的dispatchTouchEvent方法,在这个方法中,会把事件传递给Window,然后Window把事件传递给DecorView,而DecorView是什么呢?它其实是一个根View,即根布局,我们所设置的布局是它的一个子View。最后再从DecorView传递给我们的根ViewGroup。 
所以在Activity传递事件给ViwGroup的流程是这样的:Activity->Window->DecorView->ViewGroup(这是在网上找的解释,但这不是重点)

ViewGroup中的消息传递机制

接下来要借助郭大神的几行代码了。

首先我们来自定义一个布局,命名为MyLayout,继承自LinearLayout,如下所示:

[java] view
plain copy

public class MyLayout extends LinearLayout {  

  

    public MyLayout(Context context, AttributeSet attrs) {  

        super(context, attrs);  

    }  

  

}  
然后,打开主布局文件activity_main.xml,在其中加入我们自定义的布局:

[html] view
plain copy

<com.example.viewgrouptouchevent.MyLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    xmlns:tools="http://schemas.android.com/tools"  

    android:id="@+id/my_layout"  

    android:layout_width="match_parent"  

    android:layout_height="match_parent"  

    android:orientation="vertical" >  

  

    <Button  

        android:id="@+id/button1"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content"  

        android:text="Button1" />  

  

    <Button  

        android:id="@+id/button2"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content"  

        android:text="Button2" />  

  

</com.example.viewgrouptouchevent.MyLayout> 

可以看到,我们在MyLayout中添加了两个按钮,接着在MainActivity中为这两个按钮和MyLayout都注册了监听事件:

[java] view
plain copy

myLayout.setOnTouchListener(new OnTouchListener() {  

    @Override  

    public boolean onTouch(View v, MotionEvent event) {  

        Log.d("TAG", "myLayout on touch");  

        return false;  

    }  

});  

button1.setOnClickListener(new OnClickListener() {  

    @Override  

    public void onClick(View v) {  

        Log.d("TAG", "You clicked button1");  

    }  

});  

button2.setOnClickListener(new OnClickListener() {  

    @Override  

    public void onClick(View v) {  

        Log.d("TAG", "You clicked button2");  

    }  

});  



分别点击一下Button1、Button2和空白区域,打印结果如下所示:



你会发现,当点击按钮的时候,MyLayout注册的onTouch方法并不会执行,只有点击空白区域的时候才会执行该方法。你可以先理解成Button的onClick方法将事件消费掉了,因此事件不会再继续向下传递。

在郭大神的解释中直接就解释了ViewGroup的onInterceptTouchEvent方法,中间的也没解释,那我们先看看源码吧:

public boolean onInterceptTouchEvent(MotionEvent ev) {

        return false;

    }

好简单,只返回了一个false,其实上面还有好多注释,可以自己去看看。onInterceptTouchEvent方法起到拦截的作用,表示ViewGroup会不会拦截子控件的点击事件,如果为true表示拦截,这时候子控件是不会得到事件的传递的,所有事件都由ViewGroup处理。通过代码来认识:

public class MyLayout extends LinearLayout {  

  

    public MyLayout(Context context, AttributeSet attrs) {  

        super(context, attrs);  

    }  

      

    @Override  

    public boolean onInterceptTouchEvent(MotionEvent ev) {  

        return true;  

    }  

      

}  



结果显而易见,button的点击事件没有被触发,就是被拦截了呗。

好,重点来了,在Android的所有点击事件中,点击控件时会去找dispatchTouchEvent方法(这是有原因的),此时你会发现,
MyLayout 是没有这个方法的,其父类 LinearLayout也是没有这个方法的,所以再去父类找,发现LinearLayout的父类ViewGroup有这个方法,就去执行。看代码:

public boolean dispatchTouchEvent(MotionEvent ev) {  

    final int action = ev.getAction();  

    final float xf = ev.getX();  

    final float yf = ev.getY();  

    final float scrolledXFloat = xf + mScrollX;  

    final float scrolledYFloat = yf + mScrollY;  

    final Rect frame = mTempRect;  

    boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  

    if (action == MotionEvent.ACTION_DOWN) {  

        if (mMotionTarget != null) {  

            mMotionTarget = null;  

        }  

        if (disallowIntercept || !onInterceptTouchEvent(ev)) {  

            ev.setAction(MotionEvent.ACTION_DOWN);  

            final int scrolledXInt = (int) scrolledXFloat;  

            final int scrolledYInt = (int) scrolledYFloat;  

            final View[] children = mChildren;  

            final int count = mChildrenCount;  

            for (int i = count - 1; i >= 0; i--) {  

                final View child = children[i];  

                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE  

                        || child.getAnimation() != null) {  

                    child.getHitRect(frame);  

                    if (frame.contains(scrolledXInt, scrolledYInt)) {  

                        final float xc = scrolledXFloat - child.mLeft;  

                        final float yc = scrolledYFloat - child.mTop;  

                        ev.setLocation(xc, yc);  

                        child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  

                        if (child.dispatchTouchEvent(ev))  {  

                            mMotionTarget = child;  

                            return true;  

                        }  

                    }  

                }  

            }  

        }  

    }  

    boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||  

            (action == MotionEvent.ACTION_CANCEL);  

    if (isUpOrCancel) {  

        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;  

    }  

    final View target = mMotionTarget;  

    if (target == null) {  

        ev.setLocation(xf, yf);  

        if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  

            ev.setAction(MotionEvent.ACTION_CANCEL);  

            mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  

        }  

        return super.dispatchTouchEvent(ev);  

    }  

    if (!disallowIntercept && onInterceptTouchEvent(ev)) {  

        final float xc = scrolledXFloat - (float) target.mLeft;  

        final float yc = scrolledYFloat - (float) target.mTop;  

        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  

        ev.setAction(MotionEvent.ACTION_CANCEL);  

        ev.setLocation(xc, yc);  

        if (!target.dispatchTouchEvent(ev)) {  

        }  

        mMotionTarget = null;  

        return true;  

    }  

    if (isUpOrCancel) {  

        mMotionTarget = null;  

    }  

    final float xc = scrolledXFloat - (float) target.mLeft;  

    final float yc = scrolledYFloat - (float) target.mTop;  

    ev.setLocation(xc, yc);  

    if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  

        ev.setAction(MotionEvent.ACTION_CANCEL);  

        target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  

        mMotionTarget = null;  

    }  

    return target.dispatchTouchEvent(ev);  

}  

这个代码好长啊!前面一部分先不用管(虽然是有用的),是获取坐标用的,一堆x,y就知道了,重点是第13行有一个onInterceptTouchEvent,这不是拦截吗,而且还是取反!!!别急,先看第一个,disallowIntercept是指是否禁用掉事件拦截的功能,默认是false,也可以通过调用requestDisallowInterceptTouchEvent方法对这个值进行修改。那么!onInterceptTouchEvent(ev)就完全决定了是否继续执行括号里的代码,而之前如果手动设置了true,在这就是false了,就进不去方法了,而里面的代码是对子控件的操作啊,进不去的话子控件就不能接受事件传递了,还好,默认是false,所以我们平常简单使用才好使,接下来就会进入方法内部,内部监听到你的动作是ACTION_DOWN也就是按下,然后又是一堆坐标,重点是有一个for循环,是在得到子控件数量的前提下(注意这行代码final int count = mChildrenCount; )对每一个子控件进行一系列的操作,这时发现了一个很重要的判断

if (child.dispatchTouchEvent(ev))  {  

                            mMotionTarget = child;  

                            return true;  

                        } 
要执行child.dispatchTouchEvent(ev)这个方法(我们现在执行的是ViewGroup的dispatchTouchEvent),所以就要去找child也就是
子控件的dispatchTouchEvent(ev)方法,这个时候就要去执行View中的dispatchTouchEvent方法了,因为继承View的TextView和继承TextView的Button是没有这个方法的,可是View有啊!这个就是子控件的处理的,再说说一个知识点,用if判断就说明它是有返回值的,而且还是boolean型,然而只要你不做特殊处理都会返回true的,这时就会直接执行括号内的代码

最后就会返回一个true,代码执行到此就告一段落了。那么如果是在点击的子控件外的空白区域呢?这时候连     if (child.dispatchTouchEvent(ev)) 都执行不下去更别说什么返回true了,所以就会执行之后的代码,在第44行代码if (target == null) {....} 中,一般target都会是null,这样就会执行到第50行,执行return super.dispatchTouchEvent(ev);也就是View的dispatchTouchEvent(因为GroupView继承View),接下来就是View中的处理了。 
  

参考资料:http://blog.csdn.net/guolin_blog/article/details/9153747
参考资料:http://blog.csdn.net/a553181867/article/details/51287844
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: