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를 만드는 오전 볼 수 있듯이. 그런 다음 TableLayout 뷰에 tablerow를 추가합니다. 그리고
<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