谈到流式布局,有一种特性就是宽度不足,自动换行:
下面我们看看实现逻辑:
FlowLayout.java
package com.alex.flowlayout;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class FlowLayout extends ViewGroup {
public FlowLayout(Context context) {
this(context, null);
}
public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureChildren(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
/**
* 一般是定义为int top;一个top实际上是数组的下标
left : 指定矩形框左上角的x坐标
top: 指定矩形框左上角的y坐标
right: 指定矩形框右下角的x坐标
bottom:指定矩形框右下角的y坐标
*/
int width = getWidth();
int height = getHeight();
int tw = 0;
int th = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (tw + child.getWidth() < width) {
} else {
tw = 0;
th += child.getMeasuredHeight(); //超过屏幕的宽度,自动换行
}
child.layout(tw, th, tw + child.getMeasuredWidth(), th + child.getMeasuredHeight());
tw += child.getMeasuredWidth();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.alex.flowlayout.FlowLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="将进酒" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="李白" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="李白乘舟将欲行" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="忽闻岸上踏歌声" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="桃花潭水深千尺" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="不及汪伦送我情" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="离离原上草" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="一岁一枯荣" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="野火烧不尽" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="春风吹又生" />
</com.alex.flowlayout.FlowLayout>
</LinearLayout>
运行效果图如下: