2012-11-19 49 views
3

我有一个TableLayout其中有多个TableRow视图。我希望以编程方式指定行的高度。例如。是否可以指定TableRow高度?

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); 

但是这不起作用,并且默认为WRAP_CONTENT。在Android source code周围挖,我看到这个TableLayout(由onMeasure()方法触发):

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; 

好像任何试图设置行的高度将通过TableLayout覆盖。任何人都知道解决这个问题?

回答

5

好的,我想我现在已经掌握了这个。设置行高度的方法不是摆脱与TableRow连接的TableLayout.LayoutParams,而是连接到的任何TableRow.LayoutParams。简单地将一个单元格设置为所需的高度,并且(假设它是最高单元格)整行将是该高度。就我而言,我增加了一个额外的1个像素宽列集到的伎俩所期望的高度:

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)); 
1

首先,您应该使用显示系数公式将其从dps转换为像素。

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); 
+0

谢谢,但上面的引用代码的最后一行(见''findLargestCells()'')无论我指定什么,TableLayout源代码都将ViewGroup.LayoutParams的高度重置为WRAP_CONTENT。 –

相关问题