Android的onMeasure方法

來源:互聯網
上載者:User

在Android開發中,當Android原生控制項不能滿足我們的需求的時候,就需要自訂View。View在螢幕上繪製出來先要經過measure(計算)和layout(布局)。

什麼時候調用onMeasure方法?
當子View的父控制項要放置該View的時候,父控制項會傳遞兩個參數給View——widthMeasureSpec和heightMeasureSpec。這兩個參數是View可以擷取的寬高尺寸和模式值混合的int資料。可以通過int mode = MeasureSpec.getMode(widthMeasureSpec)得到模式,用int size = MeasureSpec.getSize(widthMeasureSpec)得到尺寸。

mode共有三種情況,取值分別為

MeasureSpec.UNSPECIFIED,MeasureSpec.EXACTLY,MeasureSpec.AT_MOST。


MeasureSpec.EXACTLY是精確尺寸,當我們將控制項的layout_width或layout_height指定為具體數值時如
andorid:layout_width="50dip",或者為FILL_PARENT是,都是控制項大小已經確定的情況,都是精確尺寸。

MeasureSpec.AT_MOST是最大尺寸,當控制項的layout_width或layout_height指定為WRAP_CONTENT時,控制項大小一般隨著控制項的子空間或內容進行變化,此時控制項尺寸只要不超過父控制項允許的最大尺寸即可。因此,此時的mode是AT_MOST,size給出了父控制項允許的最大尺寸。

MeasureSpec.UNSPECIFIED是未指定尺寸,這種情況不多,一般都是父控制項是AdapterView,通過measure方法傳入的模式。

可以調用setMeasuredDimenson方法,將View的高度和寬度傳入,設定子View實際的大小,告訴父控制項需要多大的空間放置子View。

以下是架構中View的onMeasure的典型實現:

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int measuredHeight = measureHeight(heightMeasureSpec);int measuredWidth = measureWidth(widthMeasureSpec);setMeasuredDimension(measuredHeight, measuredWidth);}private int measureHeight(int measureSpec) {int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);// Default size if no limits are specified.int result = 500;if (specMode == MeasureSpec.AT_MOST) {// Calculate the ideal size of your// control within this maximum size.// If your control fills the available// space return the outer bound.result = specSize;} else if (specMode == MeasureSpec.EXACTLY) {// If your control can fit within these bounds return that// value.result = specSize;}return result;}private int measureWidth(int measureSpec) {int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);// Default size if no limits are specified.int result = 500;if (specMode == MeasureSpec.AT_MOST) {// Calculate the ideal size of your control// within this maximum size.// If your control fills the available space// return the outer bound.result = specSize;}else if (specMode == MeasureSpec.EXACTLY) {// If your control can fit within these bounds return that// value.result = specSize;}return result;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.