自定义控件时在RecyclerView/ScrollView中高度不起作用

在写自定义控件时,控件嵌套在 RecyclerView 中,高度设置为 wrap_content 不起作用。

我的解决方法,在 onMeasure 中返回 childView 的高度,如下:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int childCount = getChildCount();
        int height = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            // 为ScrollerLayout中的每一个子控件测量大小
            child.measure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height) //采用最大的view的高度。
                height = h;
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
                MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

这样便能正常显示了~

猜你喜欢

转载自blog.csdn.net/wuqingsen1/article/details/86080217