未在自定义 ViewGroup 中设置 layout_width/高度的孩子



我做了一个自定义的ViewGroup,它有点工作,除了当我将视图拖放到这个ViewGroup时,编辑器说它无法将layout_width设置为子视图和layout_height。可能是什么原因造成的?

我只覆盖了两个方法 - onLayout 和 onMeasure。我相信我在onMeasure中犯了一个错误,因为我还不明白它应该如何测量儿童。

无论如何,这是我的onMeasure:

@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
            MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
    final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
            MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.AT_MOST);
    int count = getChildCount();
    for (int i = 0; i < count; ++i) {
        View child = getChildAt(i);
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
    setMeasuredDimension(mWidth, mHeight);
}

那么,如何让我的视图组的子级获取layout_with和layout_height参数呢?

附言我知道我的 ViewGroup 是固定的宽度和高度,但这就是我想要的。

事实证明,我应该使用MeasureSpec.EXACTLY。不知道它的存在。

child.measure(MeasureSpec.EXACTLY | childWidth, MeasureSpec.EXACTLY | childHeight);

附言如果有人有更好的评论答案 - 我会接受它作为答案。我很想阅读更多信息;)

最新更新