Android Dialog Fragment RecyclerView 包装内容但最大高度基于约束?

Android Dialog Fragment RecyclerView wrap content but max height based on constraints?

所以我正在努力创建一个对话框片段以允许用户从一些选项中进行选择。我在约束布局中有一个非常简单的布局。顶部是 TextView,回收器视图,然后是底部的两个按钮。

问题是,我希望 recyclerview 是包装内容,这样如果没有很多选项,对话框就会缩小。但是,如果有很多选项,我希望它展开然后开始滚动以便所有视图都在屏幕上可见。

我似乎无法克服它总是很大的情况。或者如果我只允许换行内容,对话框会变得太大以至于底部按钮都不见了。

我假设它与某些特定的约束选项有关,但我无法弄清楚它们的组合。有什么想法吗?

编辑:我知道一个简单的答案是在回收站视图上设置最大高度。我希望做同样的事情但有限制,所以它不是固定的硬高度。

EDIT2:如果视图模型的高度是固定的,那么默认情况下约束会很好地工作。不过我真的无法处理固定高度的视图模型...

谢谢

创建一个覆盖 onMeasure 方法的 customRecyclerView。

public class CustomRecyclerView extends RecyclerView{

    public CustomRecyclerView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomRecyclerView (Context context) {
        super(context);
    }

    public CustomRecyclerView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

}

你可以这样调用recyclerview

<com.example.yourpackage.CustomRecyclerView>