Search code examples
javaandroidandroid-layoutandroid-tablelayout

Changing Android TableLayout column span


So I have a TableLayout declared in XML with 2 columns in the first row and 4 columns in the second row.

 --------- ---------
|         |         |
|    A    |    B    |
|         |         |
 --------- ---------
|    |    |    |    |
|    |    |    |    |
 --------- ---------

Now I want to dynamically change the colspan of the second column (col. B) in the first row to span the whole 4 columns instead of two, and the first column (col A) to be gone, and the ability to switch back to the two-column-state. The second state of the table-layout thus would be this:

 -------------------
|                   |
|         B         |
|                   |
 --------- ---------
|    |    |    |    |
|    |    |    |    |
 --------- ---------

Initially, both of A and B are created in XML, and after loading resized and have margins added:

TableRow.LayoutParams bLp = new TableRow.LayoutParams(size, size);
bLp.setMargins(margin, 0, 0, margin);
bLp.span = 2;
b.setLayoutParams(bLp);

But if I try to change the span of that second column and hiding the first one, the only thing changing is the second column sliding to the left

a.setVisibility(View.GONE);
TableRow.LayoutParams bLp = (TableRow.LayoutParams) b.getLayoutParams();
bLp.span = 4;
b.setLayoutParams(bLp);

Changing the width of the second column to MATCH_PARENT doesn't help either, but as the Android doc for TableRow.LayoutParams says, the width isn't taken into account at all:

This set of layout parameters enforces the width of each child to be MATCH_PARENT and the height of each child to be WRAP_CONTENT, but only if the height is not specified.

Is there a way to achieve what I'm trying to do with TableLayouts?

Thanks


Solution

  • Got it now, when hiding the 'A' column I needed to set it's span to 0 additionally to set B's span to 4, so the whole code would be:

    TableRow.LayoutParams aLp = (TableRow.LayoutParams) a.getLayoutParams();
    aLp.span = 0;
    a.setLayoutParams(aLp);    
    
    a.setVisibility(View.GONE);    
    
    TableRow.LayoutParams bLp = (TableRow.LayoutParams) b.getLayoutParams();
    bLp.span = 4;
    b.setLayoutParams(bLp);