本文是参考了鸿神之后的文章之后做的一些修改与总结,添加了一些自己的笔记,增加对自定义ViewGroup的理解。文章后面会给出原文地址。
首先,什么是流式布局(FlowLayout),我个人的理解就是各个宽高不完全相同的view控件之间按照一定的规律放置,当一行或者一列中放满了控件,再放置下一个控件时,由于空间宽度或者高度不够,会自动放置到下一行或者下一列。比较常见的应用是一些热门标签,精彩评论等。比如下图中的尺寸大小标签。
其中上图中的尺寸大小作为一个整体的ViewGroup,其中放置着各个子控件,由于他们宽度大小不一,不能很好的运用现有的布局来实现,而自定义的流式ViewGroup很好的可以实现。
相比于自定义View,最重要的是onDraw()方法,自定义的ViewGroup最重要的是onMeasure(),onLayout()。一个是帮助我们去测量整个ViewGroup的子控件,另一个是帮助我们去在我们的ViewGroup中去放置我们的子控件。
1.整体分析
1、由于每一个ViewGroup都对应着一个LayoutParams,都需要指定一个LayoutParams,对于FlowLayout,我们目前只需要能够识别控件之间的margin即可,即使用MarginLayoutParams.
2、onMeasure中计算所有childView的宽和高,然后根据childView的宽和高,计算自己的宽和高。(当然,如果父控件的宽或者高不是wrap_content,直接使用父ViewGroup传入的计算值即可)
3、onLayout中对所有的childView进行布局。
2.LayoutParams
因为我们只需要支持margin,所以直接使用系统的MarginLayoutParams,重写其中的generateLayoutParams方法
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
{
return new MarginLayoutParams(getContext(), attrs);
}
3.onMeasure()方法
onMeasure完成对所有子控件的测量
/**
* 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获得它的父容器为它设置的测量模式和大小
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
Log.e(TAG, sizeWidth + "," + sizeHeight);
// 如果是warp_content情况下,记录宽和高
int width = 0;
int height = 0;
/**
* 记录每一行的宽度,width不断取最大宽度
*/
int lineWidth = 0;
/**
* 每一行的高度,累加至height
*/
int lineHeight = 0;
int cCount = getChildCount();
// 遍历每个子元素
for (int i = 0; i < cCount; i++)
{
View child = getChildAt(i);
// 测量每一个child的宽和高
measureChild(child, widthMeasureSpec, heightMeasureSpec);
// 得到child的lp
MarginLayoutParams lp = (MarginLayoutParams) child
.getLayoutParams();
// 当前子空间实际占据的宽度
int childWidth = child.getMeasuredWidth() + lp.leftMargin
+ lp.rightMargin;
// 当前子空间实际占据的高度
int childHeigh