MeasureSpec常用方法

package com.loaderman.customviewdemo;



import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;


public class MyLinLayout extends ViewGroup {
    public MyLinLayout(Context context) {
        super(context);
    }

    public MyLinLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyLinLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);//获取数值
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);//获取数值
        int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);//获取模式
        int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);//获取模式

        int height = 0;
        int width = 0;
        int count = getChildCount();
        for (int i=0;i<count;i++) {

            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            int childHeight = child.getMeasuredHeight();
            int childWidth = child.getMeasuredWidth();

            height += childHeight;
            width = Math.max(childWidth, width);
        }
      //设置 MeasureSpec.EXACTLY完全  MeasureSpec.UNSPECIFIED 不确定 MeasureSpec.AT_MOST 至多
        setMeasuredDimension((measureWidthMode == MeasureSpec.AT_MOST) ? measureWidth
                : width, (measureHeightMode == MeasureSpec.EXACTLY) ? measureHeight
                : height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int top = 0;
        int count = getChildCount();
        for (int i=0;i<count;i++) {

            View child = getChildAt(i);

            int childHeight = child.getMeasuredHeight();
            int childWidth = child.getMeasuredWidth();

            child.layout(0, top, childWidth, top + childHeight);//重新布局控件
            top += childHeight;
        }
    }
}

 

posted on 2019-01-02 16:58  LoaderMan  阅读(394)  评论(0编辑  收藏  举报

导航