以编程方式将内容添加到Android上的TableLayout

时间:2012-07-01 15:45:37

标签: android layout tablelayout

我尝试在单击按钮后向表中添加行(因此在生成活动之后)。

我的XML代码是:

       <TableLayout 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="0,1"
            android:id="@+id/result_table">
            <TableRow 
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
                <TextView
                    style="@style/MyHeader"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Col1" />
                <TextView
                    style="@style/MyHeader"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Col2"  />
            </TableRow>
        </TableLayout>

因此,当我加载活动时,我的桌子上只有我的行。然后,当我点击我的按钮时,我会这样做:

    resultTable = (TableLayout)findViewById(R.id.result_table);

    LayoutParams rowLayoutParams = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    LayoutParams cellLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    TableRow tableRow;
    TextView cellValue;
    for(Asdf a : as) {
        tableRow = new TableRow(this);
        tableRow.setLayoutParams(rowLayoutParams);

        cellValue = new TextView(this);
        cellValue.setText(a.getText());
        cellValue.setLayoutParams(cellLayoutParams);
        cellValue.setTextAppearance(this, R.style.MyText);
        tableRow.addView(cellValue);

        cellValue = new TextView(this);
        cellValue.setText("asdf");
        cellValue.setLayoutParams(cellLayoutParams);
        cellValue.setTextAppearance(this, R.style.MyText);
        tableRow.addView(cellValue);

        resultTable.addView(tableRow);
    }

    resultTable.invalidate();

但它没有添加任何东西,我确信循环迭代。我没有在logcat中收到任何警告/异常。

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

尝试更改LayoutParams添加的Views,如下所示:

TableLayout.LayoutParams rowLayoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams cellLayoutParams = TableRow.new LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);