6

我有一个里面TableLayout有多个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 源代码中四处挖掘,我在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 覆盖。有人知道解决这个问题的方法吗?

4

2 回答 2

9

好吧,我想我现在已经掌握了窍门。设置行高的方法不是摆弄TableLayout.LayoutParams附加到TableRow,而是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));
于 2012-11-19T23:21:37.000 回答
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);
于 2012-11-19T00:11:18.723 回答