动态添加到TableLayout的视图未显示

时间:2013-12-07 19:15:14

标签: android dynamic android-tablelayout

我在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。

这是deckbuilder的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>

1 个答案:

答案 0 :(得分:0)

我认为您的代码位于扩展Activity的类中。

所以你应该把

setContentView(deckBuilder);

在最后一行之后显示LinearLayout

此外,在Activity内,您可以直接使用this代替this.getApplicationContext()