需要在代碼中進行相應的設置:
在ViewGroup中的onMeasure方法裏添加一個對子元素的遍歷,並且在onLayout中添加一個佈局遍歷就實現了簡單的佈局了。
下面給出代碼:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
for(int i = 0; i < childCount; i ++){
View v = getChildAt(i);
v.measure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
for(int i = 0; i < childCount; i ++){
View v = getChildAt(i);
v.layout(l, t, r, b);
}
}
其實我們有三種在XML佈局中使用ViewGroup的方法:
1、直接使用ViewGroup
這個方法是在自己寫的ViewGroup中通過addView方法一個一個添加子View,這樣使用很不智能,但是不可否認這樣使用有其獨擋一面的地方。
2、在XML中向ViewGroup中添加View。
通過在xml文件中配置鎖包含的view
3、混合佈局
既使用XML中聲明的ViewGroup中添加View,又在自己寫的類中添加View,上述兩種的結合體
整理自:
http://www.cnblogs.com/lovewf/archive/2011/12/06/2277473.html
http://www.cnblogs.com/lovewf/archive/2012/03/20/2407389.html
http://www.cnblogs.com/lovewf/archive/2012/03/21/2407403.html