首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

View种的onMeasure方法介绍

2012-09-04 
View类的onMeasure方法介绍除非你总是需要一个100×100像素的控件,否则,你必须要重写onMeasure。onMeasure方

View类的onMeasure方法介绍
除非你总是需要一个100×100像素的控件,否则,你必须要重写onMeasure。

onMeasure方法在控件的父元素正要放置它的子控件时调用。它会问一个问题,“你想要用多大地方啊?”,然后传入两个参数——widthMeasureSpec和heightMeasureSpec。
它们指明控件可获得的空间以及关于这个空间描述的元数据。

比返回一个结果要好的方法是你传递View的高度和宽度到setMeasuredDimension方法里。
接下来的代码片段给出了如何重写onMeasure。注意,调用的本地空方法是来计算高度和宽度的。它们会译解widthHeightSpec和heightMeasureSpec值,并计算出合适的高度和宽度值。

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



Android中的View.onMeasure()
http://blog.sina.com.cn/s/blog_4b650d650100nrhr.html

热点排行