詳解Android getWidth和getMeasuredWidth

來源:互聯網
上載者:User
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的正解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.