Android ViewGroup的自定义

案例:自定义一个ViewGroup,将子view进行流式布局


image.png

流程:

  1. 测量子view的大小 → onMeasure
    测量每一个子view的宽和高,待摆放的子view的宽度如果小于当前行的剩余宽度则
    放进入,否则将其摆放到下一行。
  2. 摆放子view的位置 → onLayout (必须)
    遍历记录的每一行所有子view和每一行的高对子view进行摆放
  3. 对子view进行绘制 → onDraw
    当前案例无需重构此方法
    布局如下图


    image.png

public class FlowLayout extends ViewGroup {

    private int mHorizontalSpacing = dp2px(16); //每个item横向间距
    private int mVerticalSpacing = dp2px(8); //每个item横向间距

    private List> allLines;// 记录所有的行,一行一行的存储
    private List heights; // 记录每一行的行高

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

    private void initMeasureParams() {
        allLines = new ArrayList<>();
        heights = new ArrayList<>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        initMeasureParams(); //此方法不能在构造函数调用,生命周期

        int selfWidth = MeasureSpec.getSize(widthMeasureSpec); //获取当前类控件的宽度
        //获取内间距以便通过getChildMeasureSpec方法获取子view的度量规则
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();

        int childCount = getChildCount(); //或者子view的数量
        int lineWidthUsed = 0;  //当前行已占用了的宽度
        int lineHeight = 0;     //当前行占用最大的高度

        List lineViews = new ArrayList<>(); //记录每一行所摆放的控件
        int parentNeededWidth = 0;  //当前类控件至少所需要的宽度
        int parentNeededHeight = 0; //当前类控件至少所需要的高度

        //遍历子view进行度量,以便能获取度量之后的尺寸大小
        // childView.getMeasuredWidth()是取度量之后的大小,childView.getWidth()是取onLayout之后的大小,这里需要前者
        for (int i = 0; i < childCount; i++) {
            //获取子View;
            View childView = getChildAt(i);
            LayoutParams childLP = childView.getLayoutParams();
            //获取子view的度量规则
            int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,paddingLeft + paddingRight, childLP.width);
            int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom, childLP.height);
            //度量子view、设置子View的尺寸
            childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);

            //确定是否换行
            int childMeasureWidth = childView.getMeasuredWidth();
            int childMeasureHeight = childView.getMeasuredHeight();
            if (childMeasureWidth + lineWidthUsed + mHorizontalSpacing > selfWidth) {
                allLines.add(lineViews);
                heights.add(lineHeight);

                parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
                parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
                lineViews = new ArrayList<>();
                lineWidthUsed = 0;
                lineHeight = 0;

            }

            lineViews.add(childView);
            lineWidthUsed = lineWidthUsed + childMeasureWidth + mHorizontalSpacing;
            lineHeight = Math.max(lineHeight, childMeasureHeight);

            //最后一个子view所在的那一行需要手动加入
            if(i == childCount - 1){
                allLines.add(lineViews);
                heights.add(lineHeight);
                parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
                parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
            }
            
        }

        //确定流式布局自身的宽高
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int selfHeight = MeasureSpec.getSize(heightMeasureSpec);

        int realWidth = (widthMode == MeasureSpec.EXACTLY) ? selfWidth : parentNeededWidth;
        int realHeight = (heightMode == MeasureSpec.EXACTLY) ? selfHeight : parentNeededHeight;
        setMeasuredDimension(realWidth,realHeight); //度量之后存储该类控件自身宽高值,否则将触发测量时出现异常
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int lineCount = allLines.size();
        int curX = getPaddingLeft(); //设置子view左边的起始位置
        int curT = getPaddingTop();  //设置子view顶部的起始位置

        for (int i = 0; i < lineCount; i++) {
            List lineViews = allLines.get(i);
            int lineHeight = heights.get(i);
            for (int j = 0; j < lineViews.size(); j++) {
                View view = lineViews.get(j);
                int left = curX;
                int top = curT;
                int right = left + view.getMeasuredWidth();
                int bottom = top + view.getMeasuredHeight();
                view.layout(left, top, right, bottom); //参数值是子view距离当前控件的四个距离
                curX = right + mHorizontalSpacing;
            }
            curT = curT + lineHeight + mVerticalSpacing;
            curX = getPaddingLeft();
        }
    }

    public static int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().getDisplayMetrics());
    }


}

总结知识点:

度量规则MeasureSpec:
是view的内部类,里面定义了三个int类型的变量来表示三种模式:据传入的SpecSize来确定SpecMode, 如果传入的SpecSize是Match_parent或者是精确值,SpecMode是EXACTY,如果传入的是Wrap_content的话,SpecMode是AT_MOST, 若不对VIew的大小做出限制的话,比如listview、recycleview这些的SpecMode就是UNSPECIFIED;widthMeasureSpec和heightMeasureSpec是32位的int类型,其中包括了模式和尺寸大小,前两位表示模式,后30位表示尺寸大小。

//通过度量规则获取尺寸大小
MeasureSpec.getSize(MeasureSpec)
//获取子view的度量规则
getChildMeasureSpec(当前view的度量规则,paddingLeft + paddingRight, 子view的LayoutParams的宽高)
//对子view进行度量之后才能获取度量之后的准确值
childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
//在度量阶段获取子view的大小要取度量之后的值
int childMeasureWidth = childView.getMeasuredWidth();
// 获取度量规则的模式
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
//度量之后存储该类控件自身宽高值(度量自己),否则将触发测量时出现异常
setMeasuredDimension(realWidth,realHeight);

//获取该view到父view的距离
int left = getLeft();
//对子view进行layout摆放,方法参数是子view到父view的四个距离
view.layout(left, top, right, bottom); 
//MotionEvent中 get()和getRaw()的区别
//get() :触摸点相对于其所在组件坐标系的坐标
//getRaw() :触摸点相对于屏幕默认坐标系的坐标
1585727817(1).jpg

你可能感兴趣的:(Android ViewGroup的自定义)