Android:onMeasure()存在问题

3

我创建了一个自定义视图。如果我将该视图添加到布局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个回答

3

您不需要在调用“getSize”时调用MeasureSpec.getMode。测量规范的整个概念是将测量方式(称为规范)和相关大小组合起来。请参阅MeasureSpec.makeMeasureSpec方法的文档。因此,正确的代码应该像这样:

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

0

正确的代码应该是:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接