詳解Android 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() 區別同理。

參考:  【原】Android getWidth和getMeasuredWidth的正解

發佈了16 篇原創文章 · 獲贊 5 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章