Is it possible to specify TableRow height?
Asked Answered
H

2

6

I have a TableLayout with multiple TableRow views inside it. I wish to specify the height of the row programatically. E.g.

int rowHeight = calculateRowHeight();
TableLayout tableLayout = new TableLayout(activity);
TableRow tableRow = buildTableRow();
TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(
                                         LayoutParams.FILL_PARENT, rowHeight);
tableLayout.addView(tableRow, rowLp);

But this isn't working and is defaulting to WRAP_CONTENT. Digging around in the Android source code, I see this in TableLayout (triggered by the onMeasure() method):

private void findLargestCells(int widthMeasureSpec) {
    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (child instanceof TableRow) {
            final TableRow row = (TableRow) child;
            // forces the row's height
            final ViewGroup.LayoutParams layoutParams = row.getLayoutParams();
            layoutParams.height = LayoutParams.WRAP_CONTENT;

Seems like any attempt to set the row height will be overridden by the TableLayout. Anyone know a way around this?

Hent answered 19/11, 2012 at 0:4 Comment(0)
H
9

OK, I think I've got the hang of this now. The way to set the height of the row is not to fiddle with the TableLayout.LayoutParams attached to the TableRow, but the TableRow.LayoutParams attached to any of the cells. Simply make one cell the desired height and (assuming its the tallest cell) the entire row will be that height. In my case, I added an extra 1 pixel wide column set to the desired height which did the trick:

View spacerColumn = new View(activity);
//add the new column with a width of 1 pixel and the desired height
tableRow.addView(spacerColumn, new TableRow.LayoutParams(1, rowHeight));
Hent answered 19/11, 2012 at 23:21 Comment(0)
R
1

First of all, You should convert it from dps to pixels using the display factor formula.

  final float scale = getContext().getResources().getDisplayMetrics().density; 

  int trHeight = (int) (30 * scale + 0.5f);
  int trWidth = (int) (67 * scale + 0.5f); 
  ViewGroup.LayoutParams layoutpParams = new ViewGroup.LayoutParams(trWidth, trHeight);
  tableRow.setLayoutParams(layoutpParams);
Ryun answered 19/11, 2012 at 0:11 Comment(1)
Thanks, but the last line of the quoted code above (see findLargestCells()) in the TableLayout source code resets the height of the ViewGroup.LayoutParams to WRAP_CONTENT regardless of what I specify.Hent

© 2022 - 2024 — McMap. All rights reserved.