我有一个xml格式的TableLayout,我想以编程方式向它添加行。
这是我的代码:
LinearLayout deckBuilder = (LinearLayout) getLayoutInflater().inflate(R.layout.deckbuilder, null);
TableLayout deckGrid = new TableLayout(this.getApplicationContext());
int rows = getResources().getInteger(R.integer.deckbuilder_grid_rows);
int columns = getResources().getInteger(R.integer.deckbuilder_grid_columns);
deckGrid.setWeightSum(rows);
for (int i = 0; i < rows; ++i) {
TableRow row = new TableRow(this.getApplicationContext());
for (int j = 0; j < columns; ++j) {
ImageView iv = new ImageView(this.getApplicationContext());
row.addView(iv);
iv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1));
iv.setImageResource(R.drawable.my_image);
}
deckGrid.addView(row);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT, 1));
}
deckBuilder.addView(deckGrid);
deckGrid.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
问题是,我在行中添加的视图没有显示,行本身也没有显示。
行:3,列:5。
以下是甲板生成器的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/deckbuilder_background"
android:orientation="vertical" >
</LinearLayout>
我假设您的代码位于扩展Activity
的类中。
所以你应该放
setContentView(deckBuilder);
在最后一行之后显示CCD_ 2。
此外,在Activity
中,您可以直接使用this
来代替this.getApplicationContext()
。