Search code examples
androidandroid-recyclerviewandroid-gridlayoutstaggeredgridlayout

Variable number of columns in GridLayoutManager


I wanted to display variable number of columns in a row of GridLayoutManager while using RecyclerView. The number of columns to be displayed depends on the size of the column's TextView.

I don't know the column width as the text is being dynamically put in it.

Can anyone help? StaggeredGridLayoutManager is not solving my purpose as it customizes the height but takes fixed number of columns.


Solution

  • Take a look at the setSpanSizeLookup method of the GridLayoutManager. It lets you specify the span size for specific positions of your RecyclerView. So maybe you could use it to fit with your requirements for the variable column number.

    Edit:

    GridLayoutManager manager = new GridLayoutManager(context, 2); // MAX NUMBER OF SPACES
    manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (position == 1 || position == 6) {
                return 2; // ITEMS AT POSITION 1 AND 6 OCCUPY 2 SPACES
            } else {
                return 1; // OTHER ITEMS OCCUPY ONLY A SINGLE SPACE
            }
        }
    });
    

    When using this sort of layout manager your RecyclerView should look like this:

    +---+---+
    | 0 |   |
    +---+---+
    |   1   |
    +---+---+
    | 2 | 3 |
    +---+---+
    | 4 | 5 |
    +---+---+
    |   6   |
    +---+---+
    

    (only boxes with numbers represent items of your RecyclerView, other boxes are just empty spaces)