请问动态创建控件如何等分排列

请教动态创建控件怎么等分排列
本帖最后由 wangjimmy1994 于 2015-03-11 15:47:27 编辑
本人新手,想请教下,比如我动态创建50个按钮,怎么动态设置让它们5个一行排列在屏幕上,属性是怎么动态设置的
------解决思路----------------------
@SuppressLint("NewApi")
public class ButtonLayout extends LinearLayout {
private int cellWidth;
private int cellHeight;

public ButtonLayout(Context context) {
super(context);
}

public ButtonLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

public ButtonLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public void setmCellWidth(int w) {
cellWidth = w;
requestLayout();
}

public void setmCellHeight(int h) {
cellHeight = h;
requestLayout();
}

/**
 * 控制子控件的换行
 */
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = cellWidth;
int height = cellHeight;
int columns = (r - l) / width;//TODO
if (columns < 0) {
columns = 1;
}
int x = 0;
int y = 0;
int i = 0;
int count = getChildCount();
for (int j = 0; j < count; j++) {
final View childView = getChildAt(j);
// 获取子控件Child的宽高
int w = childView.getMeasuredWidth();
int h = childView.getMeasuredHeight();
// 计算子控件的顶点坐标
int left = x + (width - w) / 2;
int top = y + (height - h);
childView.layout(left, top, left + w, top + h);

if (i >= (columns - 1)) {
i = 0;
x = 0;
y += height;
} else {

i++;
x += width;

}
}
}

/**
 * 计算控件及子控件所占区域
 */
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 创建测量参数
int cellWidthSpec = MeasureSpec.makeMeasureSpec(cellWidth,
MeasureSpec.AT_MOST);
int cellHeightSpec = MeasureSpec.makeMeasureSpec(cellHeight,
MeasureSpec.AT_MOST);

int count = getChildCount();
for (int i = 0; i < count; i++) {
View childView = getChildAt(i);

childView.measure(cellWidthSpec, cellHeightSpec);
}

setMeasuredDimension(resolveSize(cellWidth * count, widthMeasureSpec),
resolveSize(cellHeight * count, heightMeasureSpec));

}


}

这是我项目中用到的,可以参考。