1. 程式人生 > >getWidth() 和 getMeasuredWidth() 區別

getWidth() 和 getMeasuredWidth() 區別

Google文件的英文說明:

getWidth():

Return the width of the your view.

Returns: the width of your view, in pixels

getMeasuredWidth():

The width of this view as measured in the most recent call to measure(). This should be used during measurement and layout calculations only. Use getWidth() to see how wide a view is after layout.

Returns: the measured width of this view

前提知識點:

1. 在一個類初始化時,即在建構函式當中是得不到View的實際大小的(這個我測試過,的確)。大家可以試試,getWidth()和getMeasuredWidth()得到的結果都是0,但是可以從onDraw()方法或者dispatchDraw()方法裡面獲得。可以通過呼叫invalidate()來執行onDraw()和dispatchDraw()方法。

2. 這兩個方法所得到的結果的單位是畫素即pixel

正確的理解:

getWidth(): View在設定好佈局後,整個View的寬度

getMeasuredWidth():對View上的內容進行測量後得到的View內容佔據的寬度。前提是你必須在父佈局的onLayout()方法或者此View的onDraw()方法裡呼叫measure(0,0);(measure引數的值可以知己定義),否則得到的結果和getWidth()得到的結果是一樣的。

這兩個方法最主要的區別在於,是否使用了measure()方法,同時measure()使用的位置也很重要。

getHeight() 和 get MeasuredHeight() 區別同理。