2012-12-08 34 views
1

我有一個自定義視圖,其中包含一個將控件作爲視圖的子項添加的公共函數,並且我想從我的活動中調用它。問題是我需要知道函數中視圖的大小才能放置控件。我無法重寫onMeasure來獲取這些度量,因爲我的視圖繼承自其中此函數是最終的另一個自定義視圖。我嘗試覆蓋measureChildren,但它被調用得太晚(即使在放置視圖的活動的onResume之後)。在活動調用視圖中的函數之前,我能做些什麼才能獲得大小?在添加控件之前獲取窗口大小

回答

0

一種可能性是衡量你的觀點早在活動視圖,然後設置屬性爲它的內部方法使用。

使用全局佈局偵聽器對我來說一直效果不錯。它具有能夠在佈局改變時重新測量事物的優點,例如,如果某項設置爲View.GONE或子視圖被添加/刪除。

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 

    // inflate your main layout here (use RelativeLayout or whatever your root ViewGroup type is 
    LinearLayout mainLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.main, null); 

    // set a global layout listener which will be called when the layout pass is completed and the view is drawn 
    mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() { 
      public void onGlobalLayout() { 
       // at this point, the UI is fully displayed 
      } 
    } 
); 

setContentView(mainLayout); 

http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html

0

如果你想在像素的顯示尺寸可以使用的getSize:

Display display = getWindowManager().getDefaultDisplay(); 
Point size = new Point(); 
display.getSize(size); 
int width = size.x; 
int height = size.y; 
+0

我不知道,但我知道這個問題是關於特定視圖大小不只是顯示尺寸 – fgeorgiew