我正在尝试在我的 Android 代码中动态创建按钮。我有一个字符串数组,根据它我确定要加载多少个按钮,并且每个按钮的文本都是从该字符串数组中挑选出来的。我已经在我的 Activity 上编写了下面的代码onCreate()
。代码不起作用。没有错误,但我的活动加载时看不到按钮。我确实看到屏幕上占用了一些空间,但没有按钮。有人可以在这里发现任何问题以提供帮助。
下面的代码
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>