常用类继承自ViewGroup的写法

通常情况下要写一个自定义的类继承自ViewGroup,仅需重写OnLayout这个方法就可以了, 到时再需要再上来copy

public class MyViewGroup extends ViewGroup {

    private final static int VIEW_MARGIN = 2;//定义一个边界值
    private int maxWidth = 0;
    private int maxHeight = 60;

    public MyViewGroup(Context context) {
        super(context);
    }

    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);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    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();
            int height = maxHeight; //限制子节点的高度
            lengthX += width + VIEW_MARGIN;

            lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height + arg2;
            if(width + VIEW_MARGIN > maxWidth){
                maxWidth = width + VIEW_MARGIN;
            }

            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);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值