是否可以指定TableRow高度?

时间:2012-11-19 00:04:46

标签: android android-tablelayout row-height

我有一个TableLayout,里面有多个TableRow次观看。我希望以编程方式指定行的高度。 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);

但这不起作用,并且默认为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覆盖。有人知道解决这个问题吗?

2 个答案:

答案 0 :(得分:6)

好吧,我想我现在已经掌握了这个问题。设置行高的方法不是摆弄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));

答案 1 :(得分: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);
相关问题