1.主代码
public class FlowLayout extends ViewGroup{
public FlowLayout(Context context) {
super(context);
}
public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* l t r b :表示计算当前容器的尺寸
* left : FlowLayout 在父容器距离左侧的坐标
* top: FlowLayout 在父容器距离顶部的坐标
* right: FlowLayout 在父容器距离右侧的坐标
* bottom: FlowLayout 在父容器距离底部的坐标
*
* 计算flowlayout的宽度 right-left
* 计算flowlayout的高度 bottom-top
* */
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
// 获得当前容器的宽度
int selfWidth = right - left;
// 获得容器当中子控件的数目
int childCount = getChildCount();
int cl = 10; //每一控件距离左边的边距
int ct= 10; //每一个控件距离上边的边距
// 定义一个值,表示一行当中最高的控件的高度
int lineMaxHeight = 0;
// 获取每一个子控件对象
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
// 设置子控件应该显示的位置
// 控件排布位置,从左到右,从上到下
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
int cr = cl+childWidth;
int cb = ct+childHeight;
// 判断当前子控件的右边角标是否超过了容器的宽度,如果超过了,就要换行了
if (cr>selfWidth){ //应该换行了
cl = 10; //在下一行中,这个控件距离左边的宽度10.
ct = ct + lineMaxHeight;
// 换行之后,当前控件的高度应该是这一行,最高的高度
lineMaxHeight = childHeight;
// 计算换行之后的控件的右,下
cr = cl+childWidth;
cb = ct + childHeight;
}else{ //不换行
// 不换行的情况下,判断这一行到底多高,使用原来存储的最高控件的高度和目前的控件高度对比,存储最高的。
lineMaxHeight = Math.max(lineMaxHeight,childHeight);
}
child.layout(cl,ct,cr,cb);
cl = cr;
}
}
/**
* onMeasure:
* 1.测量当前view的宽高
* 2.如果在容器当中去重写这个方法,可以测量容器中所有的子控件。
* */
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 进行子控件测量工作的方法
measureChildren(widthMeasureSpec,heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
2.布局
<?xml version="1.0" encoding="utf-8"?>
<com.animee.day4.demo06.FlowLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="200dp"
android:layout_height="100dp"
android:text="button111"/>
<Button
android:layout_width="100dp"
android:layout_height="200dp"
android:text="button222"/>
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="button333"/>
<Button
android:layout_width="105dp"
android:layout_height="100dp"
android:text="button444"/>
<Button
android:layout_width="300dp"
android:layout_height="100dp"
android:text="button555"/>
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:text="button666"/>
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:text="button777"/>
</com.animee.day4.demo06.FlowLayout>