自定义ViewGroup
类似LinearLayout
onMeasure
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
////将所有的子View进行测量,这会触发每个子View的onMeasure函数
measureChildren(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int childCount = getChildCount();
int height = 0; // 子View的高度 相加
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
height += childView.getMeasuredHeight();
}
// 类似可以得到高度,
// 根据mode 设计不同的高度和宽度
setMeasuredDimension(width, height);
}
onLayout
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int count = getChildCount();
int curHeight = t;
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
int height = child.getMeasuredHeight();
int width = child.getMeasuredWidth();
//摆放子View,参数分别是子View矩形区域的左、上、右、下边
child.layout(l, curHeight, l + width, curHeight + height);
curHeight += height;
}
}
使用
<com.xxx.xxx.XXXViewGroup>
// 添加子View
</XXXViewGroup>