1.自定义ViewGroup第一步重写OnMeasure方法;
在onMeasure方法中一般情况下我们会利用父类传给我们的参数(int widthMeasureSpec, int heightMeasureSpec)来
获取Mode和Size:
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
之后可以调用int childCount = getChildCount();
获取子元素数量
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
LayoutParams lp = child.getLayoutParams();
int childWidthSpec = getChildMeasureSpec(widthMeasureSpec, 0, lp.width);
int childHeightSpec = getChildMeasureSpec(heightMeasureSpec, 0, lp.height);
child.measure(childWidthSpec, childHeightSpec);
}
然后父元素的widthMode 和heightMode 计算自身的尺寸
switch (widthMode) {
case MeasureSpec.EXACTLY:
相当于父布局中match_parent,那么自身尺寸就可以等于widthSize
而其他情况则需要根据自己的需求判断
}
switch (heightMode) {
高度同理
}
最后一定要调用
setMeasuredDimension(width, height);//保存自身
2.自定义ViewGroup第二步重写onLayout方法;
其中方法的四个参数boolean changed, int l, int t, int r, int b是相对父容器的相对位置
利用child.getMeasuredWidth()及child.getMeasuredHeight()获取大小就可以计算位置
最后利用child.layout(left, top, right, bottom)方法摆放控件
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i)
child.getMeasuredWidth();
child.getMeasuredHeight();
child.layout(left, top, right, bottom)
}