实现宽度不足自动换行的流式布局:
FlowLayout.java
package com.jackie.flowlayout; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * Created by Jackie on 8/28/15. */ 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.jackie.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.jackie.flowlayout.FlowLayout> </LinearLayout>
效果图如下:
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/shineflowers/article/details/48055879