Set last grid to full width using GridLayoutManager (RecyclerView)
Asked Answered
I

1

6

I am using a RecyclerView with GridLayoutManager to show some items in grid pattern. It's working good and showing items in 2 columns inside grid.

But when the number of items is odd, I want that the last item has to be full width (same as width of RecyclerView).

Is there anyway to do it using GridLayoutManager or I have to build custom design?

Please help.

Infinitesimal answered 3/9, 2016 at 5:40 Comment(0)
C
19

You could use layoutManager.setSpanSizeLookup method from GridLayoutManager

Here is the way to use that

final GridLayoutManager layoutManager = new GridLayoutManager(context, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (mAdapter != null) {
                    switch (mAdapter.getItemViewType(position)) {
                        case 1:
                            return 1;
                        case 0:
                            return 2; //number of columns of the grid
                        default:
                            return -1;
                    }
                } else {
                    return -1;
                }
            }
        });

Now you have to determine the viewType in your adapter

@Override
public int getItemViewType(int position) {
    return (position == getItemCount() - 1) ? 0 : 1; // If the item is last, `itemViewType` will be 0
}

Keep building better apps!!

Calesta answered 3/9, 2016 at 6:58 Comment(2)
Saved me days and days searching. ThanksConsummate
Can anyone please help. I'm trying this but I'm getting only one column on screen. But when I remove the method setSpanSizeLookup, I'm getting total 2 columns. I'm trying to achieve the same as mentioned in the question. I have 7 items in grid and the last grid item should be fill width. Thanks in advance.Balanced

© 2022 - 2024 — McMap. All rights reserved.