你可以这样做:
1/ 使用 aRelativeLayout
作为所有这些的根ViewGroup
。
2/LinearLayout
对 的每一行使用 a Buttons
,将其设置为具有唯一 ID,并为其宽度和高度RelativeLayout.LayoutParams
设置为。用作规则,当您添加一行(第 2、3、4 等,即不是第 1 行)时,另外添加 rule ,并WRAP_CONTENT
使用它应该在下面的行的 id。CENTER_HORIZONTAL
BELOW
3/ 要确定 aButton
是否适合一行,请使用 . 获取行的宽度和RelativeLayout
(在步骤 1 中)的宽度getMeasuredWidth()
。使用那些你可以检查是否Button
适合 - 假设它们使用固定宽度。
编辑
示例(不包括第 3 步):
在您的 Activity 中添加一个成员变量ViewGroup list
,然后在 Activity.onCreate() 中:
list = new RelativeLayout(this);
list.setLayoutParams(new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
setContentView(list);
添加方法来添加按钮。
private void addButton(String btnTitle)
{
// find out how many rows we have in our relative layout
int rowCount = list.getChildCount();
int buttonCount = MY_MAX_BUTTONS_PER_ROW;
// find out how many buttons are in the last row
if (rowCount > 0) buttonCount = ((ViewGroup)list.getChildAt(rowCount-1)).getChildCount();
final ViewGroup row;
// do we have no rows, or is there no room for another button?
if (rowCount == 0 || buttonCount >= MY_MAX_BUTTONS_PER_ROW)
{
// create a row
LinearLayout newRow = new LinearLayout(this);
newRow.setId(rowCount+1);
RelativeLayout.LayoutParams rowLP = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
rowLP.addRule(CENTER_HORIZONTAL);
if (rowCount > 0) rowLP.addRule(BELOW, rowCount);
list.addView(newRow, rowLP);
rowCount++;
row = newRow;
}
// .. there's room, so add it to the last row
else
{
row = (ViewGroup)list.getChildAt(rowCount-1);
}
// create one of your buttons
// ...
button.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
row.addView(button);
}