Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify TableRow height?

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?

like image 490
Chris Knight Avatar asked Nov 19 '12 00:11

Chris Knight


2 Answers

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));
like image 142
Chris Knight Avatar answered Sep 19 '22 21:09

Chris Knight


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);
like image 22
RajeshVijayakumar Avatar answered Sep 19 '22 21:09

RajeshVijayakumar