ViewGroup全面分析
转:http://www.cnblogs.com/lqminn/archive/2013/01/23/2866543.html
一个Viewgroup基本的继承类格式如下:
1 import android.content.Context;
2 import android.view.ViewGroup;
3
4 public class MyViewGroup extends ViewGroup{
5
6 public MyViewGroup(Context context) {
7 super(context);
8 // TODO Auto-generated constructor stub
9 }
10
11 @Override
12 protected void onLayout(boolean changed, int l, int t, int r, int b) {
13 // TODO Auto-generated method stub
14
15 }
16 }
如上所示,onLayout这个方法是必须要求实现的(后面具体讲解)
假设现在如下使用这个类:
1 package com.example.myviewgroup;
2
3 import android.os.Bundle;
4 import android.widget.ImageView;
5 import android.app.Activity;
6 import android.graphics.Color;
7
8 public class MainActivity extends Activity {
9 MyViewGroup group;
10 ImageView imageView;
11
12 @Override
13 public void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15
16 group = new MyViewGroup(MainActivity.this);
17 imageView = new ImageView(this);
18 imageView.setBackgroundResource(R.drawable.ic_launcher);
19 group.addView(imageView);
20 group.setBackgroundColor(Color.GREEN);
21 setContentView(group);
22 }
23 }
你会发现界面上什么都没有,只是一片绿色,也就是说,子元素根本就没有被绘制上去。注意到上面有一个要求重载的方法onLayout(),重载如下:
1 @Override
2 protected void onLayout(boolean changed, int l, int t, int r, int b) {
3 // TODO Auto-generated method stub
4 for(int index = 0; index < getChildCount(); index++){
5 View v = getChildAt(index);
6 v.layout(l, t, r, b);
7 }
8
这个时候图像就能显示出来了。看代码应该能基本理解原因,我们给每一个child都设定了它的现实范围,使用的方法是layout,当然这里只是显示了一个View,这里只是基本。上面传进去的四个参数分别代表着ViewGroup在整个界面上的上下左右边框,也就是说,它框定了ViewGroup的可视化范围,我们要做的就是在这个范围里面安排我们的子View。再继续,假设我们这样使用自定义的ViewGroup:
1 package com.example.myviewgroup;
2
3 import android.os.Bundle;
4 import android.widget.ImageView;
5 import android.widget.LinearLayout;
6 import android.widget.TextView;
7 import android.app.Activity;
8 import android.graphics.Color;
9
10 public class MainActivity extends Activity {
11 LinearLayout layout;
12
13 MyViewGroup group;
14 TextView textView;
15 ImageView imageView;
16 @Override
17 public void onCreate(Bundle savedInstanceState) {
18 super.onCreate(savedInstanceState);
19
20 layout = new LinearLayout(this);
21 group = new MyViewGroup(this);
22 imageView = new ImageView(this);
23 textView = new TextView(this);
24
25 imageView.setBackgroundResource(R.drawable.ic_launcher);
26 textView.setText("Hello");
27
28 layout.setOrientation(LinearLayout.VERTICAL);
29 layout.setBackgroundColor(Color.WHITE);
30
31 layout.addView(imageView);
32 layout.addView(textView);
33 group.addView(layout, new LinearLayout.LayoutParams(100, 100));
34 group.setBackgroundColor(Color.GREEN);
35 setContentView(group);
36 }
37 }
我们会发现,整个界面又和以前一样,只显示一片绿色了,组件又不见了,你可以尝试改变layout的背景颜色,会发现最后显示的界面颜色也变化了,所以可以判定,我们这样子写,只是显示了最最外层的代码,并没有触发整个布局去绘制她自己的子View(这里指的是imageView和textView)。前面说到onLayout方法提供整个组件的可视范围以便于子View布局,那么子View的大小如何确定以及当子View是一个ViewGroup的时候怎么触发它去绘制自己的子View呢?这涉及ViewGroup的另外一个方法:
1 @Override
2 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
3 // TODO Auto-generated method stub
4 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
5 }
这个方法来自View,而不是ViewGroup的,文档解释如下:
Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.
通俗解释一下:这个方法其实是用来丈量View本身以及它自己的尺寸的!什么意思呢?我们先看看传入的参数是什么。传入的参数是两个int,但是实际上这两个int大有文章,是两个int的&值,解释如下:
两个参数分别代表宽度和高度的MeasureSpec,android2.2文档中对于MeasureSpec中的说明是: 一个MeasureSpec封装了从父容器传递给子容器的布局需求.每一个MeasureSpec代表了一个宽度,或者高度的说明.一个MeasureSpec是一个大小跟模式的组合值.一共有三种模式.
(1)UPSPECIFIED:父容器对于子容器没有任何限制,子容器想要多大就多大.
(2) EXACTLY:父容器已经为子容器设置了尺寸,子容器应当服从这些边界,不论子容器想要多大的空间.
(3) AT_MOST:子容器可以是声明大小内的任意大小.
暂时先这样解释着,后面再去细说。总之,这两个参数传进来的是本View(ViewGroup)显示的长和宽的值和某个模式的&值,具体取出模式或者值的方法如下:
1 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
2 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
3
4 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
而合成则可以使用下面的方法:
1 MeasureSpec.makeMeasureSpec(size, MeasureSpec.AT_MOST)
OK,上面是一些介绍,到这里可能比较混乱,整理一下:
如果让你在一个界面上绘制一个矩形,为了准确的画出这个矩形,你必须知道两件事情:1)矩形的位置(暂定为左上角的坐标);2)尺寸(长和宽),Android绘制图形的时候也要知道这两件事情,前面已经介绍了几个方法了,现在把它们联系起来(你可以想象,你用一个layoutA作为contentView,然后在layoutA里面要加一个button),Android会怎么去做呢?最正规的解释当然源自Android官方文档:http://developer.android.com/guide/topics/ui/how-android-draws.html
首先看一下View树的样子:
我们的界面基本上就是以这样子的方式组织展现的。
When an Activity receives focus, it will be requested to draw its layout. The Android framework will handle the procedure for drawing, but the Activity must provide the root node of its layout hierarchy.
(当一个Activity获取焦点的时候,它就会被要求去画出它的布局。Android框架会处理绘画过程,但是Activity必须提供布局的根节点,在上面的图上,我们可以理解为最上面的ViewGroup,而实际上还有一个更深的root)
Drawing begins with the root node of the layout. It is requested to measure and draw the layout tree. Drawing is handled by walking the tree and rendering each View that intersects the invalid region. In turn, each View group is responsible for requesting each of its children to be drawn (with the
method) and each View is responsible for drawing itself. Because the tree is traversed in-order, this means that parents will be drawn before (i.e., behind) their children, with siblings drawn in the order they appear in the tree.draw()
(绘画开始于布局的根节点,要求测量并且画出整个布局树。绘画通过遍历整个树来完成,不可见的区域的View被放弃。每个ViewGroup负责要求它的子View去绘画,每个子View则负责去绘画自己。因为布局树是顺序遍历的,这意味着父View在子View之前被画出来(这个符合常理,后面解释))。
注解:假设一个TextView设置为(FILL_PAREMT, FILL_PARENT),则很明显必须先画出父View的尺寸,才能去画出这个TextView,而且从上至下也就是先画父View再画子View,显示的时候才正常,否则父View会挡住子View的显示。
Drawing the layout is a two pass process: a measure pass and a layout pass. The measuring pass is implemented in
and is a top-down traversal of the View tree. Each View pushes dimension specifications down the tree during the recursion. At the end of the measure pass, every View has stored its measurements. The second pass happens in measure(int, int)
and is also top-down. During this pass each parent is responsible for positioning all of its children using the sizes computed in the measure pass.layout(int, int, int, int)
(布局绘画涉及两个过程:测量过程和布局过程。测量过程通过measure方法实现,是View树自顶向下的遍历,每个View在循环过程中将尺寸细节往下传递,当测量过程完成之后,所有的View都存储了自己的尺寸。第二个过程则是通过方法layout来实现的,也是自顶向下的。在这个过程中,每个父View负责通过计算好的尺寸放置它的子View。)
注解:这和前面说的一样,一个过程是用来丈量尺寸的,一个过程是用来摆放位置的。
When a View's measure()
method returns, its
and getMeasuredWidth()
values must be set, along with those for all of that View's descendants. A View's measured width and measured height values must respect the constraints imposed by the View's parents. This guarantees that at the end of the measure pass, all parents accept all of their children's measurements. A parent View may call getMeasuredHeight()
measure()
more than once on its children. For example, the parent may measure each child once with unspecified dimensions to find out how big they want to be, then call measure()
on them again with actual numbers if the sum of all the children's unconstrained sizes is too big or too small (i.e., if the children don't agree among themselves as to how much space they each get, the parent will intervene and set the rules on the second pass).
(当一个View的measure()方法返回的时候,它的getMeasuredWidth和getMeasuredHeight方法的值一定是被设置好的。它所有的子节点同样被设置好。一个View的测量宽和测量高一定要遵循父View的约束,这保证了在测量过程结束的时候,所有的父View可以接受子View的测量值。一个父View或许会多次调用子View的measure()方法。举个例子,父View会使用不明确的尺寸去丈量看看子View到底需要多大,当子View总的尺寸太大或者太小的时候会再次使用实际的尺寸去调用onmeasure().)
The measure pass uses two classes to communicate dimensions. The ViewGroup.LayoutParams
class is used by Views to tell their parents how they want to be measured and positioned. The base LayoutParams class just describes how big the View wants to be for both width and height. For each dimension, it can specify one of:
- an exact number
- FILL_PARENT, which means the View wants to be as big as its parent (minus padding)
- WRAP_CONTENT, which means that the View wants to be just big enough to enclose its content (plus padding).
不解释。
There are subclasses of LayoutParams for different subclasses of ViewGroup. For example, RelativeLayout has its own subclass of LayoutParams, which includes the ability to center child Views horizontally and vertically.
MeasureSpecs are used to push requirements down the tree from parent to child. A MeasureSpec can be in one of three modes:
- UNSPECIFIED: This is used by a parent to determine the desired dimension of a child View. For example, a LinearLayout may call
measure()
on its child with the height set to UNSPECIFIED and a width of EXACTLY240 to find out how tall the child View wants to be given a width of 240 pixels. - EXACTLY: This is used by the parent to impose an exact size on the child. The child must use this size, and guarantee that all of its descendants will fit within this size.
- AT_MOST: This is used by the parent to impose a maximum size on the child. The child must guarantee that it and all of its descendants will fit within this size.
这里前面已经提到过,也不多说,注意红色部分,也就是说可以通过设置高为一个确定值(通过EXACTLY)来看看子View在这个宽度下会怎么确定自己的高度。
OKOK,再休息一下。上面的问题可以得到解决了,往重载的ViewGroup里面添加Layout子View的时候,我们需要重载如下:
1 @Override
2 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
3 caculateWidthAndPadding(MeasureSpec.getSize(widthMeasureSpec));
4 for(int index = 0; index < getChildCount(); index++){
5
6 child.measure(MeasureSpec.makeMeasureSpec(childSize, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childSize, MeasureSpec.AT_MOST));
7 }
8 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
9 }
当然,具体的measure里面传入的参数你可以自己决定,我在这里根据widthMeasureSpec计算出一个子View的宽度(childSize),然后告诉所有的childView,你使用的最大尺寸就是childSize,不能超过(通过childSize),这个方法则会触发子View的onMeasure()方法,去设置子View的布局,由此我们可以可以看到onMeasure这个方法的作用:
1)在这个方法里面会循环调用子View的measure方法,不停的往下触发子View去丈量自己的尺寸;
2)ViewGroup继承于View,onMeasure方法在View类中的源码如下:
1 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
3 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
4 }
关于getDefaultSize方法就不多说了,看看setMeasureDimension,源码如下:
1 /**
2 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
3 * measured width and measured height. Failing to do so will trigger an
4 * exception at measurement time.</p>
5 *
6 * @param measuredWidth the measured width of this view
7 * @param measuredHeight the measured height of this view
8 */
9 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10 mMeasuredWidth = measuredWidth;
11 mMeasuredHeight = measuredHeight;
12
13 mPrivateFlags |= MEASURED_DIMENSION_SET;
14 }
看到木有,它设置了自己的宽和高!我们在重载View的时候,如果重载了onMeasure方法,就一定要调用setMeasureDimension方法,否则会抛出异常,而重载View'Group的时候,则只需要调用super.OnMeasure即可。
最后整理一下:
1)测量过程------>onMeasure(),传入的参数是本View的可见长和宽,通过这个方法循环测量所有View的尺寸并且存储在View里面;
2)布局过程------>onLayout(),传入的参数是View可见区域的上下左右四边的位置,在这个方法里面可以通过layout来放置子View;
补充:getWidth()和getMeasuredWidth()的区别
getWidth(): View在设定好布局后,整个View的宽度
getMeasuredWidth():对View上的内容进行测量后得到的View内容占据的宽度。
很简单,getWidth()就是View显示之后的width,而getMeasuredWidth,从前面的源代码就可以看出来其实是在measure里面传入的参数,具体是否一样完全要看程序最后的计算。
ViewGroup全面分析的更多相关文章
- (转载)【Android】ViewGroup全面分析
转载自:http://www.cnblogs.com/lqminn/archive/2013/01/23/2866543.html 一个Viewgroup基本的继承类格式如下: import andr ...
- Android View事件分发-从源码分析
View事件分发-从源码分析 学习自 <Android开发艺术探索> https://blog.csdn.net/qian520ao/article/details/78555397?lo ...
- [置顶]
不再迷惑,也许之前你从未真正懂得 Scroller 及滑动机制
学习本来就是从困惑中摸索问题答案的过程,能够描述出来问题就已经成功了一半.只要发现了困扰你的东西是什么,那么你就离解答出来不远了.----肯尼斯 R. 莱伯德 一直以来,Android 开发中绕不过去 ...
- 自己定义控件三部曲视图篇(二)——FlowLayout自适应容器实现
前言:我最大的梦想,就是有一天.等老了坐在摇椅上回望一生,有故事给孩子们讲--. 相关文章: <Android自己定义控件三部曲文章索引>:http://blog.csdn.net/har ...
- 一文读懂 Android TouchEvent 事件分发、拦截、处理过程
什么是事件?事件是用户触摸手机屏幕,引起的一系列TouchEvent,包括ACTION_DOWN.ACTION_MOVE.ACTION_UP.ACTION_CANCEL等,这些action组合后变成点 ...
- Android事件分发机制浅谈(二)--源码分析(ViewGroup篇)
上节我们大致了解了事件分发机制的内容,大概流程,这一节来分析下事件分发的源代码. 我们先来分析ViewGroup中dispatchTouchEvent()中的源码 public boolean dis ...
- [Android Pro] Android开发实践:自定义ViewGroup的onLayout()分析
reference to : http://www.linuxidc.com/Linux/2014-12/110165.htm 前一篇文章主要讲了自定义View为什么要重载onMeasure()方法( ...
- 点击ViewGroup时其子控件也变成pressed状态的原因分析及解决办法
这个问题,当初在分析touch事件处理的时候按理应该分析到的,可是由于我当时觉得这块代码和touch的主题不是那么紧密, 就这么忽略掉了,直到后来在这上面遇到了问题.其实这个现象做Android开发的 ...
- View Focus的处理过程及ViewGroup的mFocused字段分析
通过上篇的介绍,我们知道在对KeyEvent的处理中有非常重要的一环,那就是KeyEvent在focus view的path上自上而下的分发, 换句话说只有focus的view才有资格参与KeyEve ...
随机推荐
- Yii2 Composer
首先你必须得在本机配置token账号,里边涉及到一些git的用法,git的托管等等,具体方法如下: http://www.cnblogs.com/fnng/archive/2011/08/25/215 ...
- 记录一次项目中dubbo-admin实战部署
环境: 1.centos7 2.jdk-7u76-linux-x64.tar.gz 2.tomcat:apache-tomcat-7.0.59.tar.gz 3.zookeeper-3.4.6.tar ...
- Python每日一题 001
Github地址:https://github.com/Yixiaohan/show-me-the-code Talk is Cheap, show me the code. --Linus Torv ...
- Zookeeper集群介绍及其搭建
1 Zookeeper集群简介 1为什么搭建Zookeeper集群 大部分分布式应用需要一个主控.协调器或者控制器来管理物理分布的子进程.目前,大多数都要开发私有的协调程序,缺乏一个通用机制,协调程序 ...
- NX二次开发-UFUN打开本地文本文档uc4504
NX9+VS2012 #include <uf.h> #include <uf_cfi.h> #include <uf_ui.h> using std::strin ...
- The method setPositiveButton(int, DialogInterface.OnClickListener) in the type AlertDialog.Builder i
参考资料: http://blog.csdn.net/competerh_programing/article/details/7377950 在创建Dialog的时候,出现: The method ...
- android studio import cannot resolve symbol错误
试了好多,都不行 经过查阅和测试,发现如果上文的解决方式不可以的话,可以使用另一种: 删除项目.idea目录下的libraries目录 重新启动Android Studio 感谢作者:https:// ...
- eclipse spring boot 项目出现java.lang.ClassCastException 解决方法
问题 eclipse spring boot 项目出现java.lang.ClassCastException 解决方法: 重新生成项目
- 剑指offer——04二维数组中的查找
题目: 数组中唯一只出现一次的数字.在一个数组中除一个数字只出现一次之外,其他数字都出现了三次.请找出那个只出现一次的数字. 题解: 如果一个数字出现三次,那么它的二进制表示的每一位(0或者1)也出现 ...
- vue-cli 利用moment.js转化时间格式为YYYY年MM月DD日,或者是YYYY-MM-DD HH:MM:SS 等格式
1.在mian.js引入moment import moment from 'moment' Vue.prototype.$moment = 'moment' 2. 在main.js 设置全局过滤器 ...