没有目标的人永远为有目标的人去努力。
本讲内容:ViewGroup (一组视图)
一、ViewGroup 的介绍
View(视图)是所有UI组件的基类,而ViewGroup是容纳这些组件的容器,ViewGroup继承于View。ViewGroup是抽象类,不能直接使用它。Linearlayout等布局都是ViewGroup实现类。
譬如:利用getLayoutParams()方法和setLayoutParams()方法重新设置控件的布局
1、首先利用getLayoutParams()方法,获取控件的布局参数对象。
eg:LayoutParams lp=(LayoutParams)imageView.getLayoutParams();
2、设置该控件的layoutParams参数
eg:
3、将修改好的layoutParams设置为该控件的layoutParams.
eg:imageView.setLayoutParams(lp);
三、MeasureSpec是View的一个内部类,它封装了布局传递的参数Height和Width
四、ViewGroup的重要方法 onMeasure → onLayout → DispatchDraw
onMeasure()方法负责测量这个ViewGroup和子View的大小,onLayout()方法负责设置子View的布局,DispatchDraw()方法就是真正画上去了。
1、onMeasure()方法有两方面作用:①获得ViewGroup和子View的宽和高 ②设置子ViewGroup的宽和高
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec); //获取ViewGroup宽度
int height = MeasureSpec.getSize(heightMeasureSpec); //获取ViewGroup高度
setMeasuredDimension(width, height); //设置ViewGroup的宽高
int childCount = getChildCount(); //获得子View的个数,下面遍历这些子View设置宽高
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.measure(viewWidth, viewHeight); //设置子View宽高
}
}
先获取到了宽高再设置。顺序是先设置ViewGroup的,再设置子View。setMeasureDimension方法必须在onMeasure调用,所以子View只能调用measure()方法设置宽高,实际上measure()方法里面还是调用onMeasure()方法。
2、onLayout方法是设置子View的大小和位置。onMeasure只是获得宽高并且存储在它各自的View中,这时ViewGroup根本就不知道子View的大小,onLayout告诉ViewGroup,子View在它里面中的大小和应该放在哪里。参数int l, int t, int r, int b 就是ViewGroup在屏幕的位置。
注:参加文章http://blog.csdn.net/yuliyige/article/details/12656751