您的位置:首页 > 移动开发 > Android开发

Android MeasureSpec介绍及使用详解

2016-04-23 16:38 645 查看
说明:

一个MeasureSpec封装了父布局传递给子布局的布局要求,每个MeasureSpec代表了一组宽度和高度的要求。一个MeasureSpec由大小和模式组成。它有三种模式:UNSPECIFIED(未指定),父元素不对子元素施加任何束缚,子元素可以得到任意想要的大小;EXACTLY(完全),父元素决定子元素的确切大小,子元素将被限定在给定的边界里而忽略它本身大小;AT_MOST(至多),子元素至多达到指定大小的值。

它常用的三个函数:

  1.static int getMode(int measureSpec):根据提供的测量值(格式)提取模式(上述三个模式之一)

  2.static int getSize(int measureSpec):根据提供的测量值(格式)提取大小值(这个大小也就是我们通常所说的大小)

  3.static int makeMeasureSpec(int size,int mode):根据提供的大小值和模式创建一个测量值(格式)

/**
* 测量
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 第一步:先测量文本的区域大小
measureText();
// 第二步:对视图测量
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
// 这个方法决定了当前View的大小
setMeasuredDimension(width, height);
}

/**
* 测量高度
* @param heightMeasureSpec
* @return
*/
private int measureHeight(int heightMeasureSpec) {
int height = 0;

int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);

switch (heightMode) {
case MeasureSpec.EXACTLY:
height = heightSize;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.UNSPECIFIED:
height = mBound.height() + getPaddingBottom() + getPaddingTop();
break;

}
return height;
}

/**
* 测量宽度
* @param widthMeasureSpec
* @return
*/
private int measureWidth(int widthMeasureSpec) {
int width = 0;

int widthtSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);

switch (widthMode) {
case MeasureSpec.EXACTLY:
width = widthtSize;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.UNSPECIFIED:
width = mBound.width() + getPaddingLeft() + getPaddingRight();
break;
}
return width;
}

/**
* 对文本控件测量,得到绘制时的宽高
*/
private void measureText() {
mTextWidth = (int) mPaint.measureText(mText);

// FontMetrics fm = mPaint.getFontMetrics();
// 文本的最低处-文本的最高处
// mTextHeight = (int) Math.ceil(fm.descent - fm.top);

mBound = new Rect();
mPaint.getTextBounds(mText, 0, mText.length(), mBound);
// 获得高度
mTextHeight = mBound.height();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: