能否指定TableRow的高度?

6
我有一个包含多个 TableRow 视图的 TableLayout。我希望能够编程指定行的高度。例如:
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源代码中查找,我在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覆盖。有人知道如何解决这个问题吗?
2个回答

9

好的,我想我现在已经掌握了这个技巧。设置行高的方法不是调整附加到TableRowTableLayout.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);

2
谢谢,但是在TableLayout源代码中引用的代码的最后一行(参见“findLargestCells()”)会重置ViewGroup.LayoutParams的高度为WRAP_CONTENT,无论我指定什么。 - Chris Knight

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接