Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

getWidth()、getHeight() 老是回傳 0?是你問得太早了

想拿某個 View 的寬高,呼叫 getWidth() 與 getHeight(),結果兩邊都回 0。如果你確定這個 View 的長寬不可能是零,那問題幾乎不在 View 本身,而在呼叫的時機——你在它掛到 root view 之前就先問了,系統當然只能回你 0。

為什麼會這樣

關鍵在於 Android 的版面配置流程:一個視窗內所有元素的配置(layout)發生在這些元素都被建構完成並加入各自的父 View 之後。這個順序無可迴避——在你還不知道一個 View 裡頭裝了哪些子元件、子元件裡又裝了什麼之前,根本無從談起「怎麼排」。

所以結論很直接:在建構子裡呼叫 getWidth() 之類的方法,拿到的必然是 0。正確流程是在建構子中把所有 View 元素準備好,然後等 onSizeChanged() 被回呼——那才是你第一次得知真實尺寸的時刻,也才是設定介面元件大小的時機。

兩個實務上的替代方案

最省事的寫法是把取值動作往後延,例如放到 onWindowFocusChanged() 裡呼叫,此時視窗已取得焦點,尺寸通常已經就緒。

另外要留意一個容易踩到的細節:onSizeChanged() 有時會帶著 0 被呼叫一次,因此進入時要先檢查這個情況並立刻返回,否則後續拿它去做除法計算版面比例時就會得到 divide by zero。真正的數值會在稍後的某次回呼中送來。

以下段落整理自 Stack Overflow 上的相關回答:

Anyhow, the deal is that layout of the contents of a window happens after all the elements are constructed and added to their parent views. It has to be this way, because until you know what components a View contains, and what they contain, and so on, there's no sensible way you can lay it out.

Bottom line, if you call getWidth() etc. in a constructor, it will return zero. The procedure is to create all your view elements in the constructor, then wait for your View's onSizeChanged() method to be called -- that's when you first find out your real size, so that's when you set up the sizes of your GUI elements.

Be aware too that onSizeChanged() is sometimes called with parameters of zero -- check for this case, and return immediately (so you don't get a divide by zero when calculating your layout, etc.). Some time later it will be called with the real values.

Copyright © Linux教程網 All Rights Reserved