如何动态地将行添加到表布局中

Piy*_*hra 56 android

我在sqllite中有一些数据,每次都会更新,我点击保存按钮,我想将数据显示到表格布局中,以便为更新的数据添加更多行.

我有一些代码,但它只显示更新以前数据的更新数据,我希望在更新数据时添加更多行.

我知道这只是在表格布局中添加一行但是如何添加更多行?

TableLayout tl=(TableLayout)findViewById(R.id.maintable);    
TableRow tr1 = new TableRow(this);
tr1.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(this);
textview.setText(data);
//textview.getTextColors(R.color.)
textview.setTextColor(Color.YELLOW);
tr1.addView(textview);
tl.addView(tr1, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)

Jar*_*ith 94

这是我在经过一些试验和错误之后想出的技术,它允许您保留XML样式并避免使用a的问题<merge/>(即inflate()需要合并附加到root,并返回根节点).不需要运行时new TableRow()new TextView()s.

注意:这CheckBalanceActivity是一些示例Activity

TableLayout table = (TableLayout)CheckBalanceActivity.this.findViewById(R.id.attrib_table);
for(ResourceBalance b : xmlDoc.balance_info)
{
    // Inflate your row "template" and fill out the fields.
    TableRow row = (TableRow)LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.attrib_row, null);
    ((TextView)row.findViewById(R.id.attrib_name)).setText(b.NAME);
    ((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
    table.addView(row);
}
table.requestLayout();     // Not sure if this is needed.
Run Code Online (Sandbox Code Playgroud)

attrib_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow style="@style/PlanAttribute"  xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_name"
        android:textStyle="bold"/>
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_value"
        android:gravity="right"
        android:textStyle="normal"/>
</TableRow>
Run Code Online (Sandbox Code Playgroud)

  • 很好.与其他类型的儿童轻松移植到其他类型的布局. (2认同)

Atm*_*ram 24

在表格布局中添加行的方式可以将多个TableRow实例添加到tableLayout对象中

tl.addView(row1);
tl.addView(row2);
Run Code Online (Sandbox Code Playgroud)

等等...