2016-01-15 107 views
2

我有兩個表:TableA和TableB。 TableA的有第一排,高度爲22和表B具有高度的第一排77.我想等同於表A的第一行至表B的第一行,爲此我使用下面的代碼:Android:通過ViewTreeObserver設置視圖高度

void resizeHeaderHeight() { 
    final int[] heightA = new int[1]; 
    final int[] heightB = new int[1]; 

    TableRow TableA_Row = (TableRow) this.tableA.getChildAt(0); 
    TableRow TableB_Row = (TableRow) this.tableB.getChildAt(0); 

    final TextView textViewA = (TextView) TableA_Row.getChildAt(0); 
    final TextView textViewB = (TextView) TableB_Row.getChildAt(0); 


    ViewTreeObserver vto = textViewB.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      textViewA.getViewTreeObserver(); 
      textViewB.getViewTreeObserver(); 
      heightA[0] = textViewA.getMeasuredHeight(); 
      heightB[0] = textViewB.getMeasuredHeight(); 
      Log.d(TAG, "TableA_Row height = " + heightA[0]); 
      Log.d(TAG, "TableB_Row height = " + heightB[0]); 

      textViewA.setHeight(heightB[0]); 
     } 
    }); 
} 

但我懷疑這是否正確?

因爲當我看着logcat時,它總是打印我的日誌,但如果我刪除textViewA.setHeight(heightB[0]);它只打印一次日誌。

回答

1

假設您的佈局設計正確和設置您的textViewB的高度,這種方式是因爲它不再需要時,您應立即刪除OnGlobalLayoutListener你真正想一起去...

。您沒有這樣做,並且回調會在ViewTree佈局中發生任何更改時被調用。所以回答你的問題:你使用ViewTreeObserver的方式不是最好的...

這樣效果會更好:

void resizeHeaderHeight() { 
    TableRow TableA_Row = (TableRow) this.tableA.getChildAt(0); 
    TableRow TableB_Row = (TableRow) this.tableB.getChildAt(0); 

    final TextView textViewA = (TextView) TableA_Row.getChildAt(0); 
    final TextView textViewB = (TextView) TableB_Row.getChildAt(0); 

    textViewB.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      int heightB = textViewB.getHeight(); 
      if (heightB > 0) { 
       // removing OnGlobalLayoutListener 
       if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { 
        textViewB.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
       } else { 
        textViewB.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
       } 

       // setting height 
       textViewA.setHeight(heightB); 
      } 
     } 
    }); 
} 
+1

完美!你是天才先生Bartosz Lipinski。謝謝 )) – gigs

相關問題