Search code examples
androidandroid-recyclerviewgridlayoutmanager

Spancount in the grid layout manager i want one item in row 1 5 item in row 2 and rest 2 item per row


I want to implement grid layout manager of 1,5, and 2 item in row 1 I want one item in 2 I want 5 item then in rest I want 2 item. How to achieve this. Please help I am doing coding of the same but not able to achieve 5 in the 2nd row there is 3 only.

gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (position == 0)
                return 5;
            else if (position == 1)
                return 1;
            else
                return 2;

        }
    });

enter image description here


Solution

  • You don't mention how many total spans you have across but I guess that it is 5.

    The number of spans you define should be even divisible by the size of each item. So, divisible by 1 (of course), 5 and 2. 1*5*2=10, 10 spans will do. Create your GridLayoutManager with 10 spans.

    Now, when you want just one item in a row, return 10 from setSpanSizeLookup(). If you want 2 items, then return 5. For 5 items return 2.

    Your code will look something like this:

    mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (position == 0)
                return 10;
            else if (position < 6)
                return 2;
            else
                return 5;
    
        }
    });