Android – RecycleView’s span size

androidandroid-recyclerviewgridlayoutmanager

enter image description here

I'm trying to achieve a layout similar to the picture above
with the RecyclerView in conjunction with the GridLayoutManager, i tried setting the setSpanSizeLookup based on position but couldn't mimic the design above..

anyone could help please?

    mRecyclerView = (RecyclerView) contentView;
    mRecyclerView.setHasFixedSize(false);

    GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
    gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return 3 - (position % 3);
        }
    });

    mRecyclerView.setLayoutManager(gridLayoutManager);

..

What i'm getting
enter image description here

Best Solution

Well, you want alternate "rows" to be evenly split between two cells. Evenly split requires an even number of columns, and 3 is not an even number. So, change that to 2.

Now, you want getSpanSize() to return (by row):

  • position 0 = 2 (i.e., span both cells)
  • positions 1 and 2 = 1 (i.e., each take up one cell)
  • position 3 = 2
  • positions 4 and 5 = 1
  • etc.

(position % 3) > 0 ? 1 : 2 would seem to give you that.

Related Question