如何设置Custom ViewGroup的高度“wrap_content”(自动换行布局)

时间:2013-10-28 13:45:22

标签: android android-layout android-ui viewgroup

我想要一个可以自动更改行的布局,所以我编写了一个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;
    }


}

0 个答案:

没有答案