user1004816 user1004816 - 27 days ago 15
Android Question

Table columns in Android's TableLayout

Does anyone know whether it is possible to add columns to a TableLayout in Android? I need to display a relatively huge amount of data within a table. Obviously, this shouldn't be displayed all in one column.

You can add rows by creating a TableRow()-Object. Furthermore there's some kinda xml-parameter, but I don't know how to access it via the Java-Code.

TextView val = new TextView(this);
val.setText(args.get(i));
table.addView(val);
table.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));


I was unable to find a matching value in the TableRow.LayoutParams that worked for me. But probably I tried to use it in the wrong way.

table.addView(val,new TableRow.LayoutParams(
LayoutParams. ?? ));

Answer

As you add new views to the tablet row each view becomes a new "column".

So, if you do something like this (assuming your row data is in List rowData and your column data is in a List in rowData.

for (RowData rd : rowData)
{
    TableRow row = new TableRow(this);
    for (DataPoint dp : rd.getDataPoints())
    {
       TextView tv = new TextView(this);
       tv.setText(dp.getText());

       /* any other styling stuff here */

       row.addView(tv);
     }
 table.addView(row);
}

That will result in a table, with multiple columns, all within a single table.

For layout params, you can use:

new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, (float) 5);

What that means is 0 width, wrap content on height, then a relative "weight" for the width. Android will layout your columns nicely with this.