Android:onMeasure()的问题

时间:2010-05-13 13:03:26

标签: android layout

我制作了自定义视图。如果我将视图添加到布局XML文件中,并将高度设置为fill_parent“specSize”返回0.为什么?

代码:

    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int measuredHeight = 90;

        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(MeasureSpec.getMode(heightMeasureSpec));

        if(specMode != MeasureSpec.UNSPECIFIED){
         measuredHeight = specSize;
        }
        setMeasuredDimension(60, measuredHeight);
}

有谁知道我如何获得fill_parent的高度?

2 个答案:

答案 0 :(得分:3)

你不需要在调用'getSize'时调用MeasureSpec.getMode整个测量规范的想法是结合测量方式(知道为Spec)和相关的大小。请参阅MeasureSpec.makeMeasureSpec方法的文档。正确的代码如下所示:

int widthSpec = MeasureSpec.getMode(widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);

答案 1 :(得分:0)

正确的代码是:

int specMode = MeasureSpec.getMode(heightMeasureSpec);     ----This was already correct
int specSize = MeasureSpec.getSize(heightMeasureSpec);     ----This is corrected.