我想在我的Android代码中动态地创建按钮。我有一个字符串数组defnied根据我找出多少个按钮加载和每个按钮的文本从字符串数组中挑选。我在下面的活动onCreate()
上写下了相同的代码。代码不起作用。没有错误,但我的活动加载时没有看到按钮。我确实看到屏幕上有一些空间被占用,但按钮不在那里。有人可以找到任何问题来帮助。在TableLayout中动态加载按钮
代码如下
TableLayout table = (TableLayout) findViewById(R.id.tableLayoutCategoryButtons);
int buttonsInRow = 3;//number of buttons in each row
String[] itemNames = getResources().getStringArray(R.array.categories_array);
int numRows = (itemNames.length/buttonsInRow);
//round off numRows to next integer. e.g. for 10 items in array there will be (10/3) +1=4 rows
if (itemNames.length % buttonsInRow != 0)
numRows++;
TableRow[] tr = new TableRow[numRows];
Button[] buttons = new Button[itemNames.length];
int rowcount = 0;
for (int i = 0; i < itemNames.length; i++) {
buttons[i] = new Button(table.getContext(), null, android.R.attr.buttonStyleSmall);
buttons[i].setText(itemNames[i]);
buttons[i].setTextColor(Color.BLACK);
buttons[i].setVisibility(View.VISIBLE);
buttons[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tr[rowcount] = new TableRow(table.getContext());
tr[rowcount].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tr[rowcount].addView(buttons[i]);
//change of tablerow, once a multiple of 3 reached.
if (((i + 1) % buttonsInRow == 0) && (i != 0)) {
tr[rowcount].setVisibility(View.VISIBLE);
table.addView(tr[rowcount]);
rowcount++;
}
}
正如你可以看到我创建一个TableRows每三个按钮在一排。然后将Tablerow添加到TableLayout视图。而我的活动xml低于
<RelativeLayout
android:id="@+id/relativeLayoutCategoryHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TableLayout
android:id="@+id/tableLayoutCategoryButtons"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="0,1,2">
</TableLayout>
</RelativeLayout>
谢谢。现在IT工作。你是对的,为每一行添加一个线性布局。 – user1938357