Kyle
Kyle

Reputation: 1524

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

So I'm working on creating a dialog fragment to allow user to choose from some options. I have a pretty simple layout inside a constraint layout. TextView on top, recycler view, then two buttons at the bottom.

The problem is, I want the recyclerview to be wrap content, so that if there aren't a lot of options, the dialog will shrink down. However, if there are a lot of options, i'd like it to expand but then start scrolling so all views are visible on the screen.

I can't seem to get past the situation where either it constantly is large. Or if I just allow wrap content, the dialog will grow so large the bottom buttons are missing.

I'm assuming it has something to do with some particular constraint options, but I can't figure out the combination. Any ideas?

EDIT: I know an easy answer is to set a max height on the recycler view. I'm hoping to do that same thing but with constraints, so its not a fixed hard height.

EDIT2: It looks like the constraints will work nicely with wrap as default if the view model's height is fixed. I really can't deal with a fixed height view model though...

Thanks

Upvotes: 4

Views: 1264

Answers (1)

L2_Paver
L2_Paver

Reputation: 626

Create a customRecyclerView that override onMeasure method.

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);
    }

}

you can call the recyclerview like this

<com.example.yourpackage.CustomRecyclerView>

Upvotes: 1

Related Questions