Android下自动折行 效果
关于自动折行,网上面已经有很多实现代码了,我在之前也实现过,最近再次用上这个效果,发现之前自己写的代码很丑陋,于是进行了重构,现在把代码放出来。
import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; public class FlowLinearLayout extends LinearLayout { public FlowLinearLayout(Context context) { super(context); } public FlowLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int maxWidth = MeasureSpec.getSize(widthMeasureSpec); int childCount = getChildCount(); int measuredX = 0; int measuredY = 0; int raw = 1; int maxRowItemHeight = 0; for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() == View.GONE) { return; } child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int width = child.getMeasuredWidth(); int height = child.getMeasuredHeight(); if (height > maxRowItemHeight) { measuredY = getMeasuredY(measuredY, raw, maxRowItemHeight, height); maxRowItemHeight = height; } measuredX += width; if (measuredX > maxWidth) { measuredX = width; raw++; measuredY += height; maxRowItemHeight = 0; } } measuredY += getPaddingTop() + getPaddingBottom(); setMeasuredDimension(maxWidth, measuredY); } private int getMeasuredY(int measuredY, int raw, int maxRowItemHeight, int height) { if (raw == 1) { measuredY = height; } else { measuredY += height - maxRowItemHeight; } return measuredY; } @Override protected void onLayout(boolean changed, int l, int t, int rightBorder, int b) { int childCount = getChildCount(); int maxRowItemHeight = 0; int measuredX = getPaddingLeft(); int measuredY; int raw = 1; for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() == View.GONE) { return; } int width = child.getMeasuredWidth(); int height = child.getMeasuredHeight(); if (height > maxRowItemHeight) { maxRowItemHeight = height; } measuredX += width; if (measuredX > rightBorder) { measuredX = getPaddingLeft() + width; raw++; } measuredY = getPaddingTop() + raw * maxRowItemHeight; child.layout(measuredX - width, measuredY - maxRowItemHeight, measuredX, measuredY); } } }
总共代码100行,实现了显示效果如下图
小遗憾是没有写magin,所以子元素很紧凑,大家可以自己写一个magrin参数,添加上对于的效果。