android 之onMeasure

http://www.eoeandroid.com/thread-102385-1-1.html 参考

http://blog.csdn.net/hqdoremi/article/details/9980481 更为详细:

 

 

 onMeasure方法在控件的父元素正要放置它的子控件时调用.它会问一个问题,“你想要用多大地方啊?”,   然后传入两个参数——widthMeasureSpec和   heightMeasureSpec

 

它们会译解widthHeightSpec和heightMeasureSpec值,并计算出合适的高度和宽度值.

 例1

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec, expandSpec);
}

 

例2:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int hight = MeasureSpec.getSize(heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        setMeasuredDimension(
                MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(hight, MeasureSpec.EXACTLY));

    }

 

  MeasureSpec的三种模式:

MeasureSpec.EXACTLY //确定模式,父View希望子View的大小是确定的,由specSize决定;

MeasureSpec.AT_MOST //最多模式,父View希望子View的大小最多是specSize指定的值;

MeasureSpec.UNSPECIFIED //未指定模式,父View完全依据子View的设计值来决定;

 

 

  1:精确模式(EXACTLY):  代表的是精确的尺寸;   (width或height为fill_parent时,容器在布局时调用子view的measure方法传入的模式是EXACTLY,因为子view会占据剩余容器的空间,所以它大小是确定的)

  2:最大模式(AT_MOST): 代表的是最大可获得的空间而当设置为wrap_content时,容器传进去的是AT_MOST, 表示子view的大小最多是多少,这样子view会根据这个上限来设置自己的尺寸

  3:未指定模式(UNSPECIFIED):父布局没有给子布局任何限制,子布局可以任意大小,对于控件尺寸来说,没有任何参考意义。

 

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

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

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

  setMeasuredDimension(int, int)设置实际大小。

posted on 2013-06-04 10:58  yujian_bcq  阅读(396)  评论(0编辑  收藏  举报

导航