Variable number of columns in GridLayoutManager

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

I do not know the width of the column, because the text is dynamically placed in it.

Can anyone help? StaggeredGridLayoutManager does not solve my goal, since it adjusts the height, but fixes the number of columns.

+5
source share
2 answers

Take a look at the setSpanSizeLookup method of the GridLayoutManager . It allows you to specify the range size for specific positions of your RecyclerView . Therefore, perhaps you can use it to suit your requirements for the column number of the variable.

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 such a manager layout, your RecyclerView should look like this:

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

(only fields with numbers represent elements of your RecyclerView , other fields are just empty spaces)

+17
source

If you want to make such an option as: 4 columns, 5 columns, 6 columns ... You can get an MMC (at least a few common ones) between these numbers (60) and set the GridLayoutManager:

 GridLayoutManager manager = new GridLayoutManager(context, 60); // set the grid with the MMC manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return 12; // 60/12 = 5 Columns } }); 
Then you could return 10, 12 or 15 for 6, 5 and 4 columns on getSpanSize ()
+1
source

Source: https://habr.com/ru/post/1232196/


All Articles