标签:
import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /***/ public class AutoWrapLayout extends ViewGroup {
//支持的最大行数 10行,可以根据需要调整 private int[] mRawArray = new int[10]; private int mPadding = 3; public AutoWrapLayout(Context context) { this(context, null); } public AutoWrapLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AutoWrapLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMeasuredWidth(); int height = getMeasuredHeight(); int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); } int rawChildWidthSum = 0; int maxChildHeight = 0; for (int i = 0, raw = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); if (maxChildHeight < childHeight) maxChildHeight = childHeight; rawChildWidthSum += childWidth; mRawArray[raw] = i; if (rawChildWidthSum > width) { mRawArray[raw]--; raw++; rawChildWidthSum = 0; } mRawArray[raw] = i; } } int allRawHeight = 0; for (int aRawArray : mRawArray) { if (aRawArray > 0) { allRawHeight += (maxChildHeight + mPadding * 3); } else {
break
}
} setMeasuredDimension(width, allRawHeight); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int left = 0; int top = t; int maxChildHeight = 0; for (int i = 0; i < mRawArray.length; i++){//every raw //i <=> raw number int aRawArray = mRawArray[i]; // Handle first raw particularly. if (i == 0) { if (aRawArray > 0) { for (int j = 0; j <= aRawArray; j++) {// column final View child = getChildAt(j); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); left += childWidth; top = 0; if (maxChildHeight < childHeight) maxChildHeight = childHeight; child.layout(left - childWidth, 2, left, top + maxChildHeight + 3); } } continue; } if (aRawArray > 0) { left = 0; for (int j = mRawArray[i - 1] + 1; j <= aRawArray; j++) {// column final View child = getChildAt(j); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); left += childWidth; top = i * maxChildHeight + maxChildHeight + t; if (maxChildHeight < childHeight) maxChildHeight = childHeight; child.layout(left - childWidth, top - maxChildHeight + 2, left, top + 3); } } else { break; } } } }
标签:
原文地址:http://www.cnblogs.com/sxzheng/p/5006817.html