您的位置:首页 > 其它

meaurespec的再次认识

2016-04-13 15:00 295 查看
自定义一个view,重写onMeasure,onLayout,onDarw方法,onMeasure方法中有几个容易混淆的地方

首先,MeasureSpec的运用,可以用onMeasure方法的参数int widthMeasureSpec, int heightMeasureSpec,

int widthSpecMode=MeasureSpec.getMode(widthMeasureSpec);根据提供的测量值(格式)提取模式

int widthSpecSize=MeasureSpec.getSize(widthMeasureSpec);根据提供的测量值(格式)提取大小值(这个大小也就是我们通常所说的大小)

通过模式可以判断自定义控件view的宽或高采用的模式,根据模式给view设值,例如:

  if (widthSpecMode==MeasureSpec.AT_MOST&&heightSpecMode==MeasureSpec.AT_MOST){

  //宽高都是wrap_content

            setMeasuredDimension(200,200);

        }else if (widthSpecMode==MeasureSpec.AT_MOST){
//宽是wrap_content,高是marth_parent

            setMeasuredDimension(200,heightSpecSize);

        }else if (heightSpecMode==MeasureSpec.AT_MOST){

            setMeasuredDimension(widthSpecSize,200);

        }else{

//宽高都是用marth_parent

super.onMeasure(widthMeasureSpec, heightMeasureSpec);



其次,注意onMeasure方法里调用了 setMeasuredDimension方法,这个方法必须由onMeasure(int, int)来调用,来存储测量的宽,高值。

注意区别MeasureSpec的makeMeasureSpec(int size,int mode)方法,这个方法根据提供的大小值和模式创建一个测量值(格式)。

makeMeasureSpec设置一个带有mode(模式)跟size(高度或宽度)的测量值,将这个值传入onMeasure方法中作为参数(宽或高),所以也会被setMeasuredDimension方法调用。

参考文章:http://www.tuicool.com/articles/qmEVNju
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: