我想要一个可以自动换线的布局,所以我写了一个viewGroup来实现它。但是虽然我设置了属性“wrap_content”,但AutomaticWrapLayout的高度超过了孩子的视图,它是一个完整的屏幕。并且在它的顶部是一个空白区域。但我不希望视图组很高,所以我想找到一些方法来解决它。
public class AutomaticWrapLayout extends ViewGroup {
private final static int VIEW_MARGIN=2;
public AutomaticWrapLayout(Context context) {
super(context);
}
public AutomaticWrapLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutomaticWrapLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
final int count = getChildCount();
int row=0;// which row lay you view relative to parent
int lengthX=arg1; // right position of child relative to parent
int lengthY=arg2; // bottom position of child relative to parent
for(int i=0;i<count;i++){
final View child = this.getChildAt(i);
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
lengthX+=width+VIEW_MARGIN;
lengthY=row*(height+VIEW_MARGIN)+VIEW_MARGIN+height+arg2;
if(lengthX>arg3){
lengthX=width+VIEW_MARGIN+arg1;
row++;
lengthY=row*(height+VIEW_MARGIN)+VIEW_MARGIN+height+arg2;
}
child.layout(lengthX-width, lengthY-height, lengthX, lengthY);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
for (int index = 0; index < getChildCount(); index++) {
final View child = getChildAt(index);
child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
}
int measureWidth = measureWidth(widthMeasureSpec);
int measureHeight = measureHeight(heightMeasureSpec);
setMeasuredDimension(measureWidth, measureHeight);
}
private int measureWidth(int pWidthMeasureSpec) {
int result = 0;
int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);
int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);
switch (widthMode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = widthSize;
break;
}
return result;
}
private int measureHeight(int pHeightMeasureSpec) {
int result = 0;
int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
int heightSize = MeasureSpec.getSize(pHeightMeasureSpec);
switch (heightMode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = heightSize;
break;
}
return result;
}
}