public class CustomViewGroup extends ViewGroup{
public CustomViewGroup(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
/**
* 依据specMode的值,如果是AT_MOST,specSize 代表的是最大可获得的空间;如果是EXACTLY,specSize 代表的是精确的尺寸;如果是UNSPECIFIED,对于控件尺寸来说,没有任何参考意义。
*/
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY)
{
throw new IllegalStateException("ApplicationsStackLayout can only be used with "
+ "measure spec mode=EXACTLY");
}
measureChildren(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
int mTotalHeight = 0;
// 遍历所有子视图
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
// 获取在onMeasure中计算的视图尺寸
int measureHeight = childView.getMeasuredHeight();
int measuredWidth = childView.getMeasuredWidth();
if(i==1){
childView.layout(50, mTotalHeight, measuredWidth+50, mTotalHeight + measureHeight);
}else
childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight + measureHeight);
mTotalHeight += measureHeight;
}
}
}
使用自定义的ViewGroup
<CustomViewGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff">
<TextView android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="fasdjflsadjlf"
android:background="#555555"/>
<TextView android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="fasdjflsadjlf"
android:background="#999999"/>
</CustomViewGroup>