在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;}