View的测量

将自定义View的基本知识记录下来,供以后查看吧


    MeasureSpec是一个32位的int值,其中高2位为测量模式,低30位为测量的大小,在计算中使用位运算的原因是为了提高并优化效率。

    测量模式可以分为三种:

    EXACTLY

   精确值模式,即给控件layout_width或layout_height属性指定具体数值,或指定为match_parent

    AT_MOST

   最大值模式,当控件的layout_width或layout_height属性指定为wrap_content时,控件大小一般随着控件的子控件或内容的变化而变化,此时控件的尺寸只要不超过父控件允许的最大尺寸即可。

    UNSPECIFIED

    不指定其大小测量模式,通常绘制定义View才会使用。


    View类默认的onMeasure()方法只支持Exactly模式,要让View支持wrap_content属性,必须重写onMeasure()方法来指定wrap_content的大小。onMeasure()方法最终是将宽高作为参数传给setMeasureDimension()方法,以下为自定义测量的方法,如果给wrap_content就会默认给200px。

@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){
    setMeasureDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
}

private measureWidth(int measureSpec){
    int result=0;
    int specMode=MeasureSpec.getMode(measureSpec);
    int specSize=MeasureSpec.getSize(measureSpec);

    if(spacMoed==MeasureSpac.EXAXTLY){
        result=specSize;
    }else{
        result=200;
        if(specMode==MeasureSpec.AT_MOST){
            result=Math.min(result,specSize);
        }    
    }
    return reslut;
}


猜你喜欢

转载自blog.csdn.net/gf6873/article/details/79841001