测量 ViewGroup 的大小

Measure size of ViewGroup

我有一个包含一个子项 (ImageButton) 的 ViewGroup。 我希望 viewGroup 具有其子项的确切大小。

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int desiredWidth = getChildAt(0).getMeasuredWidth();
        int desiredHeight = getChildAt(0).getMeasuredHeight();

        int width = resolveSize(desiredWidth,widthMeasureSpec);
        int height = resolveSize(desiredHeight,heightMeasureSpec);

        setMeasuredDimension(width,height);
    }

我通过 getMeasuredWidth() 和 getMeasuredWidth() 获取子尺寸 (ImageButton),但它们 return 0 值。

您没有测量 child 视图,因此它的宽度和高度尚未设置(尚未)。

要么在你的方法中调用 super.onMeasure(...) 让你的超级 class 测量 child,要么你自己调用 child.measure(widthMeasureSpec, heightMeasureSpec).