Search code examples
androidandroid-recyclerviewgridlayoutmanager

Set last grid to full width using GridLayoutManager (RecyclerView)


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.


Solution

  • 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!!