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++;
}
}
ご覧のとおり、3 つのボタンがそれぞれ 1 行に並んだ TableRows を作成しています。そして、テーブル行を 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>