一般在剛開始開發android時,會犯一個錯誤,即在View的建構函式中擷取getWidth()和getHeight(),當一個view對象建立時,android並不知道其大小,所以getWidth()和getHeight()返回的結果是0,真正大小是在計算布局時才會計算,所以會發現一個有趣的事,即在onDraw( ) 卻能取得長寬的原因。
如何在建構函式中如何取得長寬。
Java代碼
- width = activity.getWindowManager().getDefaultDisplay().getWidth();
- height = activity.getWindowManager().getDefaultDisplay().getHeight();
activity為你的Activity對象
The getWidth and getHeight methods will return 0 if the view has not yet been inflated. For example, if you are trying to access it in the onCreate
of the Activity, you'll get zero.
在UI 組件還未顯示在介面之前調用getWidth和getHeight方法通常會得到0。所以不能在onCreate方法裡獲得組件的width和height.
可以通過以下兩種方法獲得:
1 |
float width=activity.getWindowManager().getDefaultDisplay().getWidth(); |
2 |
float height=activity.getWindowManager().getDefaultDisplay().getHeight(); |
或者重寫onWindowFocusChanged,在這個方法裡擷取
1 |
public void onWindowFocusChanged( boolean hasFocus) { |
2 |
super .onWindowFocusChanged(hasFocus); |
-----------------------------------------------------------------------------------------------
我們都知道在onCreate()裡面擷取控制項的高度是0,這是為什麼呢?
說明等onCreate方法執行完了,我們定義的控制項才會被度量(measure),所以我們在onCreate方法裡面通過view.getHeight()擷取控制項的高度或者寬度肯定是0,因為它自己還沒有被度量,也就是說他自己都不知道自己有多高,而你這時候去擷取它的尺寸,肯定是不行的.
android getWidth() getHeight() 方法返回的值為0
使用一個view的getWidth() getHeight() 方法來擷取該view的寬和高,返回的值卻為0。如果這個view的長寬很確定不為0的話,那很可能是你過早的調用這些方法,也就是說在這個view被加入到rootview之前你就調用了這些方法,返回的值自然為0.
解決該問題的方法有很多,主要就是延後調用這些方法。可以試著在onWindowFocusChanged()裡面調用這些方法。
以下是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.
參考連結:
http://www.2cto.com/kf/201208/146660.html