先上核心代码:
[Java] 纯文本查看 复制代码 class ll extends ViewGroup
{
int n=2,H,V,max;
ll(Context c){super(c);}
void set(int n, int h, int v)
{
this.n = n;
this.H = h;
this.V = v;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
max = maxWidth - getPaddingLeft() - getPaddingRight();
int x = 0;
int y = getPaddingTop() + getPaddingBottom();
int row = 0;
for (int i = 0; i < getChildCount(); i++)
{
View v = getChildAt(i);
if (v.getVisibility() != View.GONE)
{
v.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int height = v.getMeasuredHeight();
x += 1;
y = row * height + height;
if (x > n)
{
x = 1;
row++;
y = row * height + height;
}
}
}
y += (row + 2) * V;
setMeasuredDimension(maxWidth, y);
}
@Override
protected void onLayout(boolean p1, int l, int t, int r, int b)
{
l = getPaddingLeft();
t = getPaddingTop();
int x = l;
int y = 0;
int row = 1;
for (int i = 0; i < getChildCount(); i++)
{
View v = getChildAt(i);
if (v.getVisibility() != View.GONE)
{
int width = (max - H) / n - H;
int height = v.getMeasuredHeight();
x += width + H;
y = row * (height + V);
if (x > l + max)
{
x = l + H + width;
row++;
y = row * (height + V);
}
v.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
v.layout(x - width, y - height, x, y);
}
}
}
}
核心代码基于尘哥bamboy
再上调用的
[Java] 纯文本查看 复制代码 ll f=new ll(this);
f.setPadding(28,8,28,8);
f.set(3,32,32);//一行的排布数,横间距,纵间距 |