Android 自定义ViewGrou——FlowLayout

目录

自定义ViewGroup

Measure测量方法

Measure测量​编辑

ViewGroup 为 childView 指定测量模式

重写OnMeasure()

2种遍历测量所有子 View

ViewGroup中的 onLayout()

FlowLayout Demo


自定义ViewGroup

        所有父控件(布局)都是 ViewGroup的子类,ViewGroup是一个抽象类,它里面有一个抽象方法 onLayout(),这个方法的作用就是摆放它所有的子控件(安排位置),因为是抽象类,在布局文件中可以使用View但是不能直接使用 ViewGroup。

  • 自定义 View 需要重写:
    • onMeaure():确定 View 的大小。
    • onDraw() :绘制 View 的内容。
  • 自定义 ViewGroup 需要重写:
    • onMesure():测量子 view 的大小,才能确定 ViewGroup 的大小。
    • onLayout() :确定子 View 的位置。
    • onDraw():不是必须重写的,甚至不一定会被调用,只有当ViewGroup拥有 background 或 调用setWillNotDraw(false) 后才会回调 onDraw() 。

Measure测量方法

  • measureChild():测量某一个child的宽高,不支持margin值。
    • 调用 getChildMeasureSpec() 生成子视图的 MeasureSpec ,成功后通知子视图执行 measure()。
  • measureChildWithMargins():测量某一个child的宽高,考虑margin值。
    • 调用 getChildMeasureSpec() 生成子视图的 MeasureSpec ,成功后通知子视图执行 measure()。
    • 注意:measureChildWithMargins和measureChild区别:measureChild父控件支不支持margin属性。
  • measureChildren():遍历ViewGroup中所有的子控件。
  • getChildCount():返回子View的数量。
  • MeasureSpec.getSize/getMode(widthMeasureSpec/heightMeasureSpec):在 widthMeasureSpec 或 heightMeasureSpec 中,模式表示了父视图对子视图尺寸的约束方式
  • getChildMeasureSpec():根据父视图的 MeasureSpec 和 子视图的 LayoutParams 属性来生成 子视图的 MeasureSpec。
    • Android 为 ViewGroup 提供子View测量模式默认方法:ViewGroup.getChildMeasureSpec()和 View.getDefaultSize()一样。

ViewGroup 类中默认提供了几个测量子 View 的方法,源码

//测量子视图
protected void measureChild(View child, int parentWidthMeasureSpec,int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom, lp.height);
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
    final int size = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < size; ++i) {
        final View child = children[i];
        if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
    }
}
//测量子视图并计算其Margin
protected void measureChildWithMargins(View child,int parentWidthMeasureSpec, int widthUsed,int parentHeightMeasureSpec, int heightUsed) {
    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin+ widthUsed, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin+ heightUsed, lp.height);
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
//获取子View的MeasureSpec,对于ViewGroup来说,这是非常重要的一个方法!!
int getChildMeasureSpec(int spec, int padding, int childDimension) {        ...    }

Measure测量

  • 测量的时候父控件的onMeasure() 会遍历所有的子控件,挨个调用子控件的measure() ,measure() 会调用onMeasure。然后会调用setMeasureDimension() 保存测量的大小(得到子控件大小,确定ViewGroup大小),一次遍历下来,第一个子控件以及这个子控件中的所有子控件都会完成测量工作;然后开始测量第二个子控件…;最后父控件所有的子控件都完成测量以后会调用setMeasureDimension方法保存自己的测量大小。
  • ViewGroup在执行Layout过程是使用遍历来调用子View的Layout方法,并制定其具体显示的位置,从而来决定其布局位置。

ViewGroup 为 childView 指定测量模式

        ViewGroup会为childView指定测量模式,getChildMeasureSpec方法默认的测量模式,可查看源码。

  • 父视图为 EXACTLY
    • 子视图大小为 固定值、match_parent,子视图为 EXACTLY模式。
    • 子视图大小为 WRAP_CONTENT,子视图为 AT_MOST 模式。
  • 父视图为 AT_MOST
    • 子视图大小为 固定值,子视图为 EXACTLY模式。
    • 子视图大小为 MATCH_PARENT、WRAP_CONTENT,子视图为 AT_MOST模式。
  • 父视图为 UNSPECIFIED
    • 子视图大小为 固定值,子视图为 EXACTLY模式。
    • 子视图大小为 MATCH_PARENT、WRAP_CONTENT,UNSPECIFIED

源代码:getChildMeasureSpec()

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    int specMode = MeasureSpec.getMode(spec);
    int specSize = MeasureSpec.getSize(spec);

    int size = Math.max(0, specSize - padding);

    int resultSize = 0;
    int resultMode = 0;

    switch (specMode) {
    // Parent has imposed an exact size on us
    case MeasureSpec.EXACTLY:
        if (childDimension >= 0) {
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child wants to be our size. So be it.
            resultSize = size;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size. It can't be
            // bigger than us.
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent has imposed a maximum size on us
    case MeasureSpec.AT_MOST:
        if (childDimension >= 0) {
            // Child wants a specific size... so be it
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child wants to be our size, but our size is not fixed.
            // Constrain child to not be bigger than us.
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size. It can't be
            // bigger than us.
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent asked to see how big we want to be
    case MeasureSpec.UNSPECIFIED:
        if (childDimension >= 0) {
            // Child wants a specific size... let them have it
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child wants to be our size... find out how big it should
            // be
            resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
            resultMode = MeasureSpec.UNSPECIFIED;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size.... find out how
            // big it should be
            resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
            resultMode = MeasureSpec.UNSPECIFIED;
        }
        break;
    }
    //noinspection ResourceType
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

重写OnMeasure()

2种遍历测量所有子 View

  • 第一种:调用 measureChildren(),一次性测量所有的子 View。遍历所有子 View,根据 measuredWidth 和 mesuredHeight 计算 ViewGroup 尺寸。
  • 第二种:调用 measureChild 或 measureChildWithMargin(区别,ViewGroup 的 LayoutParams 是否允许 margin)来测量子 View,并在这个过程中计算 ViewGroup 的大小。

        在计算完毕后,调用setMeasuredDimension(w, h)来设置最终的测量结果。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
   
    // 获取子类数量
    int childCount = getChildCount();
    
    // 获取当前的padding
    int paddingLeft = getPaddingLeft();
    int paddingRight = getPaddingRight();
    int paddingTop = getPaddingTop();
    int paddingBottom = getPaddingBottom();
    
    // 获取ViewGroup父类的宽高
    int selfWidth = MeasureSpec.getSize(widthMeasureSpec); // ViemGroup解析的父亲给我的宽度
    int selfHeiht = MeasureSpec.getSize(heightMeasureSpec);// ViemGroup解析的父亲给我的高度
    
    int parentNeedWidth = 0;//measure过程中,子View要求的父ViewGroup的宽
    int parentNeedHeight = 0;//measure过程中,子View要求的父ViewGroup的高
    
     // 保存大小
     List<View> lineView = new ArrayList<>(); // 保存一行中的所有的view
     int lineWidthUsed = 0;// 记录这行已经使用了多宽的size
     int lineHeight = 0; // 一行的高
    
    // 先度量孩子
    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);
        LayoutParams childLP = childView.getLayoutParams();
        // 将layoutParent转变为measureSpec,根据父类的widthMeasureSpec去测量子类该给什么值。
        int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, paddingLeft + paddingRight, childLP.width);
        int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom, childLP.height);
        // 测量子类
        childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        
        // 获取子类view的宽高
        int childMeasuredWidth = childView.getMeasuredWidth();
        int childMeasuredHeight = childView.getMeasuredHeight();
        
        // 如果需要换行
        if (childMeasuredWidth + lineWidthUsed > selfWidth) {
            // 一旦换行,判断当前行需要的宽和高了,所以此时要记录下来
            parentNeedHeight = parentNeedHeight + lineHeight;
            parentNeedWidth = Math.max(parentNeedWidth, lineWidthUsed);
            // 重置
            lineView = clear();
            lineWidthUsed = 0;
            lineHeight = 0;
        }
        
        //view 是分行layout的,所以要记录每一行有哪些view,这样可以方便layout布局
        lineView.add(childView);
        // 每行都会有自己的宽和高
        lineWidthUsed = lineWidthUsed + childMeasuredWidth;
        lineHeight = Math.max(lineHeight, childMeasuredHeight);
    }
    
    // 根据子View的度量结果,来重新度量自己 ViemGroup
    // 作为一个viewGroup,它自己也是一个 item,它的大小也需要根据它的父亲给它提供的宽高来度量
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    
    int realWidth = (widthMode==MeasureSpec.EXACTLY) ? selfWidth:parentNeedWidth;
    int realHeight = (heightMode==MeasureSpec.EXACTLY)? selfHeiht:parentNeedHeight;
    
    // 在度量自己,保存
    setMeasuredDimension(realWidth,realHeight);
}

ViewGroup中的 onLayout()

  • ViewGroup中的onLayout() 是一个抽象方法,所有ViewGroup的子类都必须重写这个方法。
  • LinearLayout、RelativeLayout等布局,都重写了这个方法,在内部按照各自的规则对子视图进行布局的。
@Override protected abstract void onLayout(boolean changed, int l, int t, int r, int b);

        自定义一个布局,只要能够包含一个子视图,并且让子视图正常显示出来就可以了

FlowLayout Demo

示例图

public class FlowLayout extends ViewGroup {

    private List<View> mLineViews;//每一行的子View
    private List<List<View>> mViews;//所有的行 一行一行的存储
    private List<Integer> mHeights;//每一行的高度

    public FlowLayout(Context context) {
        this(context, null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    private void init() {
        mLineViews = new ArrayList<>();
        mViews = new ArrayList<>();
        mHeights = new ArrayList<>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
         // 获取ViewGroup父类宽高值
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        // 记录当前行的宽度和高度
        int lineWidth = 0;// 宽度是当前行子view的宽度之和
        int lineHeight = 0;// 高度是当前行所有子View中高度的最大值

        //整个流式布局的宽度和高度
        int flowLayoutWidth = 0;//所有行中宽度的最大值
        int flowLayoutHeight = 0;// 所以行的高度的累加

        init();

        int childCount = this.getChildCount();

        // 先测量子View,再根据子View尺寸,计算自己的
        for (int i = 0; i < childCount; i++) {
            View child = this.getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);

            //获取到当前子View的测量的宽度/高度
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 已经放入的孩子的宽度 + 准备放入的孩子的宽度 大于 总宽度 就换行
            if (lineWidth + childWidth > widthSize) {
                mViews.add(mLineViews);
                mLineViews = new ArrayList<>();//创建新的一行
                // 所有行中 最宽的一行 作为 流式布局的宽
                flowLayoutWidth = Math.max(flowLayoutWidth, lineWidth);
                // 流式布局的高度为所有行的高度相加
                flowLayoutHeight += lineHeight;
                mHeights.add(lineHeight);
                lineWidth = 0;
                lineHeight = 0;
            }

            mLineViews.add(child);
            lineWidth += childWidth;

            // 获取行中最高的子View
            lineHeight = Math.max(lineHeight, childHeight);
        }

        // 保存尺寸给后面用
        setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : flowLayoutWidth
                , heightMode == MeasureSpec.EXACTLY ? heightSize : flowLayoutHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int currX = 0;
        int currY = 0;
        int lineCount = mViews.size();
        // 处理每一行
        for (int i = 0; i < lineCount; i++) {
            List<View> lineViews = mViews.get(i);
            int lineHeight = mHeights.get(i);
            int size = lineViews.size();
            // 处理每一行中的View
            for (int j = 0; j < size; j++) {
                View child = lineViews.get(j);
                // 子View的左上右下
                int left = currX;
                int top = currY;
                int right = left + child.getMeasuredWidth();
                int bottom = top + child.getMeasuredHeight();
                // 布局子View
                child.layout(left, top, right, bottom);
                currX += child.getMeasuredWidth();
            }
            currY += lineHeight;
            currX = 0;
        }
    }
}

activity_main.xml
 

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.dfg.flowlayout.FlowLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mFlowLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="55dp"
            android:text="儿时凿壁偷了谁家的光" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="亲爱的" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:text="我是不是看上去真的很胖" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="这个问题实在不好回答" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:text="公交车上,有一美女" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="和一个外国人用英语交谈" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="交谈声很大" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="美女聊得很开学" />

    </com.dfg.flowlayout.FlowLayout>

</ScrollView>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值