Setting number of columns programmatically in TableLayout
Asked Answered
P

1

6

I have an XML layout which contains a TableLayout with an unknown number of TableRows... The number of Rows will be established durin runtime, what I do know though is that I want two columns... So I have a couple of questions regarding this :

    - is there a way to set the whole TableLayout to have 2 columns ?

- is there a way programmatically to give an id to the (during runtime) created TableRows which will be placed within the TableLayout, so I can reference them later on from other parts of the software ?

Preston answered 28/4, 2010 at 13:48 Comment(0)
J
6

You can build your table rows via XML parts and LayoutInflater. Say you had this as your table_cell.xml:

<TextView android:id="@+id/text"
    android:text="woot" />

And this as your table_row.xml (unless you're doing something fancy with your TableRow, you may not need to put it in it's own XML file, and instead just create it programmatically. The result will be the same):

<TableRow />

Assuming your TableLayout reference was called "table", you could do something like this:

TableLayout table = (TableLayout)findViewById(R.id.table);
LayoutInflater inflater = getLayoutInflater();

for(int i = 0; i < 5; i++) {
    TableRow row = (TableRow)inflater.inflate(R.layout.table_row, table, false);
    View v = (View)inflater.inflate(R.layout.table_cell, row, false);
    row.addView(v);
    v = (View)inflater.inflate(R.layout.table_cell, row, false);
    row.addView(v);

    // you can store your reference to `row` here for later use
    table.addView(row);
}

With this technique, you can still set up your layout in XML, making it easier to read/organize/edit, and you still have programmatic control over how many columns and rows are in the table. You can also store references to each table row for later use.

Jeggar answered 28/4, 2010 at 16:29 Comment(2)
thx ! I have been trying it and it does retrieve my table_cell. In my case it's an ImageButton, but the problem is that even though I added the layout_gravity="center" to it it won't add itthe way I'd expect it to. Also padding on those same ImageButtons won't work. In my XML version it does work without using padding. I want to have 2 ImageButtons per row. Because the two summed up are smaller than the screen width in my XML based solution they are placed with space inbetween them. What it does now is placing them one against the other so it actually seems like one long button instead of twoPreston
All the padding and layout_gravity stuff should work just as it normally does. There is no difference doing it this way. Are you sure you have that stuff correct? Perhaps it would be good for another question on SO?Jeggar

© 2022 - 2024 — McMap. All rights reserved.