MeasureSpec介紹及使用詳解

一個MeasureSpec封裝了父佈局傳遞給子佈局的佈局要求,每一個MeasureSpec表明了一組寬度和高度的要求。一個MeasureSpec有大小和模式組成。他有三種模式:html

UNSPECIFIED 未指定 父元素不對字元素施加任何束縛,子元素能夠獲得任意想要的大小。函數

EXACTLY 徹底 父元素決定自元素的大小,子元素將被限定在給定的邊界裏而忽略它自己的大小。佈局

AT_MOST 至多 子元素多達到指定大小的值spa

它經常使用的三個函數:.net

static int getMode(int measureSpec)根據提供的測量值(格式)提取模式(上述三個模式之一)code

static int getSize(int measureSpec)根據提供的測量值(格式)提取大小值(這個大小也就是咱們一般所說的大小)xml

static int makeMeasureSpec(int size,int mode):根據提供的大小值和模式建立一個測量值(格式)htm

首先一個咱們經常使用到的一個有用的函數,View.resolveSize(int size,int measureSpec)blog

 

[html]  view plain  copy
 
  1. public static int resolveSize(int size, int measureSpec) {  
  2.          int result = size;  
  3.          int specMode = MeasureSpec.getMode(measureSpec);  
  4.          int specSize =  MeasureSpec.getSize(measureSpec);  
  5.          switch (specMode) {  
  6.          case MeasureSpec.UNSPECIFIED:  
  7.              result = size;  
  8.              break;  
  9.          case MeasureSpec.AT_MOST:  
  10.              result = Math.min(size, specSize);  
  11.              break;  
  12.          case MeasureSpec.EXACTLY:  
  13.              result = specSize;  
  14.              break;  
  15.          }  
  16.          return result;  
  17.      }  

 

9023         public static int makeMeasureSpec(int size, int mode) {
9024             return size + mode;
9025         }

 

 

 

[html]  view plain  copy
 
  1. private void measureItem(View child) {  
  2.          ViewGroup.LayoutParams p = child.getLayoutParams();  
  3.          if (p == null) {  
  4.              p = new ViewGroup.LayoutParams(  
  5.                      ViewGroup.LayoutParams.MATCH_PARENT,  
  6.                      ViewGroup.LayoutParams.WRAP_CONTENT);  
  7.          }  
  8.    
  9.          int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,  
  10.                  mListPadding.left + mListPadding.right, p.width);  
  11.          int lpHeight = p.height;  
  12.          int childHeightSpec;  
  13.          if (lpHeight > 0) {  
  14.              childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);  
  15.          } else {  
  16.              childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);  
  17.          }  
  18.          child.measure(childWidthSpec, childHeightSpec);  
  19.      }  

 

 

 注意,使用EXACTLY和AT_MOST一般是同樣的效果,若是你要區別他們,那麼你就要使用上面的函數View.resolveSize(int size,int measureSpec)返回一個size值,而後使用你的view調用setMeasuredDimension(int,int)函數。ip

 

8406     protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
8407         mMeasuredWidth = measuredWidth;
8408         mMeasuredHeight = measuredHeight;
8409 
8410         mPrivateFlags |= MEASURED_DIMENSION_SET;
8411     }

  而後你調用view.getMeasuredWidth,view.getMeasuredHeigth 返回的就是上面函數裏的mMeasuredWidth,mMeasuredHeight的值。

相關文章
相關標籤/搜索