我想在我的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