2013-06-13 44 views
2

我通過代碼創建了我的層次結構視圖,然後我在Activity中使用我的根視圖做了setContentView(),就像參數一樣。當android計算視圖的寬度和高度

我需要知道一個視圖在運行時的寬度和高度,但如果我做getWidth()getHeight(),我得到0.如果我等幾秒鐘,我得到正確的寬度或高度。

我只想知道在什麼時候android計算寬度/視圖高度。我的代碼不是優秀的

謝謝!

+0

http://stackoverflow.com/questions/4074937/android-how-to-get-a-custom-views-height-and-width – Sam

回答

2

你不說,你試圖測量的看法,但我的猜測是它在的onCreate()或的onResume()>

在你的onCreate試試這個()。

// 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() { 
       // measure your views here 
      } 
    } 

這裏,mainLayout是對佈局根視圖組的引用。

如果佈局在第一次繪製之後調整大小(在代碼中添加視圖,方向更改等),也會調用此選項,以便始終獲得正確的值。

+0

感謝:添加此。 view.post似乎不適用於所有設備。關於同一主題的另一個討論在這裏:http://stackoverflow.com/a/13944263/969325 – Warpzit

3

這是因爲在onCreate()佈局尚未計算。因此,您需要添加一個GlobalLayoutListener以瞭解何時佈局已計算並放置在屏幕中。

final View view = findViewById(R.id.root); 
ViewTreeObserver vto = view.getViewTreeObserver(); 
      vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
       @Override 
       public void onGlobalLayout() { 
        ViewTreeObserver vto = view.getViewTreeObserver(); 
        vto.removeGlobalOnLayoutListener(this); 
       } 
      }); 

其中root是根佈局(LinearLayout,RelativeLayout即)。用@ + id/root分配你的根佈局。

+0

你仍然打字,因爲我張貼:) – Simon

+0

哈哈是啊你發佈了幾秒鐘前的答案:P – Carnal

+0

+1有這裏沒有代碼的版權。 GUD回答... –

0

爲清楚起見,根據本Android documentation

當活動接收焦點,它將被要求要繪製它 佈局。

...還測量視圖尺寸。

重點收到onResume後,並在方法後丟失。

0

你可以使用一些View類。對於學習我新的東西

@Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) { 

     super(w,h,oldw,oldh); 
     if(oldw == 0 && w !=0){ 
     ... 
     // w and h is what you want 
    } 
相關問題