neqopa
neqopa

Reputation: 119

RecyclerView items with different heights with FlexboxLayoutManager

How can I display my recycleview items in a row while keeping their original height?

I want to use a recycleviewer with FlexboxLayoutManager. Every item normally having their own height depending on their content. However, every recycleview item on the same row always ending up with an equal height somehow.

How can I display my recycleview items in a row while respecting their original height?

I need the items to be displayed like this:

Correct one

What I tried without success:

Fault one (The small items always stretches)

My code where I set the layout manager:

        adapter = new ProductAdapter(getContext(), productsList);

        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setFlexDirection(FlexDirection.ROW);
       // layoutManager.setAlignContent(AlignContent.CENTER);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

I have tried this layoutManager.setAlignContent(AlignContent.CENTER); However you can't set alignContent in a FlexboxLayoutManager for a recycleviewer. The app crash because alignContent is for FlexboxLayout (not manager).

EDITED: When using a StaggeredGridLayoutManager , this will solve the problem. However you will lose the responsive behaviour of the FlexboxLayoutManager.

I created my own responsive behaviour for a StaggeredGridLayoutManager:

 DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
        int spanCount = (int) (dpWidth / 222);  // 222=total space for 1 item incl. margin

            recyclerView.setLayoutManager(new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));

Upvotes: 3

Views: 2088

Answers (2)

Nil Oleart
Nil Oleart

Reputation: 354

Try something like this as your RecyclerView layout manager:

recycler.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

Upvotes: 4

Sdghasemi
Sdghasemi

Reputation: 5598

From your image I think what you need is StaggeredGridLayoutManager

Upvotes: 0

Related Questions