行无法使用代码动态添加到Android中的表格布局

时间:2015-03-29 07:24:54

标签: android dynamic android-tablelayout

我只想在运行时添加新行,并尝试使用以下代码..

java file ::>

TableLayout caseTable = (TableLayout) findViewById(R.id.caseTable);
TableRow caseRow = new TableRow(this);
caseRow.setOrientation(TableRow.VERTICAL);
EditText name = new EditText(this);
name.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
name.setText("Name __");
caseRow.addView(name);
caseTable.addView(caseRow,new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));

xml file ::>

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/caseTable"
    android:stretchColumns="0,1,2,3">
    <TableRow>
        <TextView android:text="Case" />
        <TextView android:text="Details" />
    </TableRow>
</TableLayout>

我想在现有的行下面添加新行。我从stackOverFlow处获取了代码。但它没有用。谢谢。

1 个答案:

答案 0 :(得分:1)

只是简单地使用下面的代码以编程方式添加TableRow,以前它不起作用,因为您正在尝试将TableLayout参数添加到EditText。

        TableLayout caseTable = (TableLayout) findViewById(R.id.caseTable);
        TableRow caseRow = new TableRow(this);
        caseRow.setOrientation(TableRow.VERTICAL);
        EditText name = new EditText(this);
        //name.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
        name.setText("Name __");
        caseRow.addView(name);
        caseTable.addView(caseRow,new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));