您的位置:首页 > 其它

111_约束子控件宽高

2016-05-13 23:26 190 查看

约束子控件的宽高

刚刚的基础代码

public class FlowLayout extends LinearLayout {

    public FlowLayout(Context context) {

        super(context);

    }

 

    public FlowLayout(Context context, AttributeSet attrs) {

        super(context, attrs);

    }

 

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

    }

 

    @Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

 

    @Override

    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        super.onLayout(changed, l, t, r, b);

    }

}

 

 

我们不能让子控件的宽比父控件的宽还大

所以我们要约束子控件的宽

 

        //可用的宽和高

        int availableWidth = widthSize - getPaddingLeft() - getPaddingRight();

        int availableHeight = heightSize - getPaddingTop() - getPaddingBottom();

        int childCount = getChildCount();

        //约束子控件

        for (int i = 0; i < childCount; i++) {

            View childView = getChildAt(i);

            //重新定义子控件宽高

            int widthSpec = MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST);

            int heightSpec = MeasureSpec.makeMeasureSpec(availableHeight, MeasureSpec.AT_MOST);

            //新的测量规则生效

            childView.measure(widthSpec, heightSpec);

            //新的宽高

            int childMeasuredWidth = childView.getMeasuredWidth();

            in
4000
t childMeasuredHeight = childView.getMeasuredHeight();

            //子控件间距

            ViewGroup.LayoutParams layoutParams = childView.getLayoutParams();

        }

 

 

设定子控件的参数

    @Override

    public LayoutParams generateLayoutParams(AttributeSet attrs) {

        //返回子控件的LayoutParams

        MarginLayoutParams marginLayoutParams = new MarginLayoutParams(getContext(),attrs);

        return (LayoutParams) marginLayoutParams;

    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: