How to add rows dynamically into table layout
Solution 1:
Here's technique I figured out after a bit of trial and error that allows you to preserve your XML styles and avoid the issues of using a <merge/>
(i.e. inflate() requires a merge to attach to root, and returns the root node). No runtime new TableRow()
s or new TextView()
s required.
Code
Note: Here CheckBalanceActivity
is some sample Activity
class
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.
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>
Solution 2:
The way you have added a row into the table layout you can add multiple TableRow
instances into your tableLayout
object
tl.addView(row1);
tl.addView(row2);
etc...
Solution 3:
You might be better off using a ListView with a CursorAdapter (or SimpleCursorAdapter).
These are built to show rows from a sqlite database and allow refreshing with minimal programming on your part.
Edit - here is a tutorial involving SimpleCursorAdapter and ListView including sample code.
Solution 4:
You are doing it right; every time you need to add a row, simply so new TableRow()
, etc. It might be easier for you to inflate
the new row from XML
though.