2012-08-22 184 views
15

如何獲取在xml中定義爲fill_parent的高度和寬度的線性佈局的寬度和高度?我嘗試過測量方法,但我不知道它爲什麼沒有給出確切的價值。在oncreate方法完成之前,我需要在Activity中使用這些值。獲取運行時的佈局高度和寬度android

+0

IIRC在測量之前,您無法獲得任何東西的高度/寬度。當onSizeChanged被調用時,它被分配,如果你重載onLayout所有視圖應該有一個高度和寬度 – tom502

+0

@ tom502你可以給我一個鏈接或一段代碼?這將是非常有益的。 – MGDroid

回答

31

想我必須得在XML定義的LinearLayout寬度。我必須通過XML獲取它的參考。定義LinearLayoutl作爲實例。

l = (LinearLayout)findviewbyid(R.id.l1); 
ViewTreeObserver observer = l.getViewTreeObserver(); 
     observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

      @Override 
      public void onGlobalLayout() { 
       // TODO Auto-generated method stub 
       init(); 
      l.getViewTreeObserver().removeGlobalOnLayoutListener(
        this); 
     } 
    }); 

protected void init() { 
     int a= l.getHeight(); 
      int b = l.getWidth(); 
Toast.makeText(getActivity,""+a+" "+b,3000).show(); 
    } 
    callfragment(); 
} 
+1

注意!在onCreate完成之前它不會給你值。 Alhought我已經在onCreate方法中調用它的覆蓋方法將被稱爲遲了。所以看起來你的應用程序運行緩慢,但它解決了我的目的。 – MGDroid

5

寬度和高度值是在創建佈局之後設置的,當元素被放置後,它們被測量。在第一次調用onSizeChanged時,parms將爲0,所以如果您使用該檢查。

這裏更詳細一點 https://groups.google.com/forum/?fromgroups=#!topic/android-developers/nNEp6xBnPiw

這裏http://developer.android.com/reference/android/view/View.html#Layout

下面是如何使用onLayout:

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    int width = someView.getWidth(); 
    int height = someView.getHeight(); 
} 
2

你可以在配置變更監聽器添加到您的佈局,獲得最新的高度和寬度,甚至最後改變之前的一個。

在API級別11

添加監聽將被調用時,視圖變化 的邊界由於佈局處理。

LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.my_linear_layout); 
myLinearLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { 
     @Override 
     public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { 
      // Preventing extra work because method will be called many times. 
      if(height == (bottom - top)) 
       return; 

      height = (bottom - top); 
      // do something here... 
      } 
    }); 
3

得到它的工作,你需要檢查所需的高度值是否大於0 - 和第一然後取出onGlobalLayout聽衆,做任何你想要的高度。監聽者不斷地調用它的方法,並且在第一次調用時不能保證視圖被正確測量。

final LinearLayout parent = (LinearLayout) findViewById(R.id.parentView); 
    parent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      int availableHeight = parent.getMeasuredHeight(); 
      if(availableHeight>0) { 
       parent.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
       //save height here and do whatever you want with it 
      } 
     } 
    }); 
+0

這樣做 - 謝謝。刪除監聽器調用已從API級別16棄用。本文描述如何支持早期和後期API的調用http://stackoverflow.com/a/23741481/2162226 – gnB

相關問題