2014-05-08 126 views
0

我嘗試獲取線性佈局的大小。我總是得到iactualHeight = 0下面的代碼:如何獲得線性佈局的大小

li=(LinearLayout)findViewById(R.id.textviewerbuttonlayout); 
li.requestLayout(); 
int iactualHeight=li.getLayoutParams().height; 

我的佈局定義如下:

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_height="fill_parent" 
android:layout_width="fill_parent" 
android:background="#FFFFFF" 
android:id="@+id/textviewerlayout" 
android:orientation="vertical"> 

<WebView 
    android:id="@+id/mywebview" 
    android:layout_width="fill_parent" 
    android:layout_height="0dp" 
    android:layout_weight="22" /> 

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/textviewerbuttonlayout" 
    android:layout_width="fill_parent" 
    android:layout_height="0dp" 
    android:layout_weight="2" 
    android:background="#FFFFFF" 
    android:orientation="horizontal" > 
.... BUTTONS ..... 


</LinearLayout> 
</LinearLayout> 

有人什麼想法?

回答

2

你不會得到價值unitl onCreate finishes.so在onResume()onStart()

int height= li.getHeight(); 
int width = li.getWidth(); 

添加這些其他的選項是使用globallayoutlistener(如果你想獲得的onCreate高度),這樣你會得到通知當李(你的佈局)被添加。

ViewTreeObserver observer= li.getViewTreeObserver(); 
observer.addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
      public void onGlobalLayout() { 
       Log.d("Log", "Height: " + li.getHeight()); 
       Log.d("Log", "Width: " + li.getWidth()); 
      } 
     }); 
+0

謝謝。在onStart我仍然得到0.在OnGlobalLayoutListener我得到正確的值。所以你的快速答案是非常有用的。 –

0

問題是你要求身高太早。看看how android draws views

得到保證的高度,最簡單的方法是使用addOnLayoutChangedListener:

View myView = findViewById(R.id.my_view); 
    myView.addOnLayoutChangedListener(new OnLayoutChangeListener() { 

      @Override 
      public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, 
        int oldBottom) { 
       // its possible that the layout is not complete in which case 
       // we will get all zero values for the positions, so ignore the event 
       if (left == 0 && top == 0 && right == 0 && bottom == 0) { 
        return; 
       } 

       int height = top - bottom; 
      } 
});