ViewGroup是一种特别的View,它可以作为一个视图组件的容器,从而在里面添加其他的视图组件。这是它的相关继承关系:
从这图片中,我们就不会感到陌生了。
继承GroupView时,onLayout()是必须重写的。
其中很重要的三个方法是:onMeasure(),onLayout(),ondispatchDraw()。
他们分别执行组件的测量,位置和绘制,执行顺序:
子组件的个数不为0,当添加子组件的时候会引起容器的状态发生变化。从而子组件的大小和位置就需要重新测量,所以会调用多次。
下面我们做个小实例:
public class MyViewGroup extends ViewGroup {
public MyViewGroup(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MyViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyViewGroup(Context context) {
super(context);
// TODO Auto-generated constructor stub
// ImageView mButton = new ImageView(context);
// mButton.setBackgroundColor(Color.GREEN);
// addView(mButton);
}
/**
* 设置组件的大小
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 获取该ViewGroup的实际长和宽 涉及到MeasureSpec类的使用
int specSize_Widht = MeasureSpec.getSize(widthMeasureSpec);
int specSize_Heigth = MeasureSpec.getSize(heightMeasureSpec);
// 设置本ViewGroup的宽高
setMeasuredDimension(specSize_Widht, specSize_Heigth);
}
/**
* 设置组件的位置
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
View view = null;
// 获取在onMeasure中计算的视图尺寸
int lastTop = 0;
int height = 10;
// l:左边距 t:上边距 r:与左边距的差值为宽 b:与上边距的差值为高(默认分别为满屏 ,为: 0:0:480:724)
for (int index = 0; index < getChildCount(); index++) {
view = getChildAt(index);
lastTop += index * 50;
// 所以 高度就50(lastTop+50 -lastTop)
view.layout(l, lastTop, r, lastTop + 50);
}
}
/**
* 绘制组件
*/
@Override
protected void dispatchDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.dispatchDraw(canvas);
}
}
活动界面添加两个ImageView:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
MyViewGroup group = new MyViewGroup(this);
group.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
ImageView imgA = new ImageView(this);
imgA.setBackgroundColor(Color.CYAN);
group.addView(imgA);
ImageView imgB = new ImageView(this);
imgB.setBackgroundColor(Color.BLUE);
group.addView(imgB);
setContentView(group);
}
结果: