2012-11-19 51 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。 –

相關問題