子View们的宽度加起来超过一行,会自动换行显示。java
核心就两步:git
再复杂的自定义View都是这样从最简单的形式,不断增长代码,迭代出来的 github
最简单的自定义ViewGroup:app
public class FlowLayout extends ViewGroup { 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); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childCount = getChildCount(); int layoutWidth = r-l; int left = 0; int right = 0; int top = 0; for (int i = 0; i < childCount; i++) { View view = getChildAt(i); // 换行:比较right,right若是大于Layout宽度,那么要换行 right = left + view.getMeasuredWidth(); if (right > layoutWidth) { left = 0; right = left + view.getMeasuredWidth(); top += view.getMeasuredHeight(); } getChildAt(i).layout(left, top, right, top + view.getMeasuredHeight()); left += view.getWidth(); } } }
上述这些我也都实现了,但还有一个我没有去弄,对gravity的支持(由于其非必需就暂时不加,我现有其它事),若是你有兴趣完成它,能够fork,弄好了pull request。ide
完整代码查看this