问题
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.
回答1:
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)
回答2:
If you want to make a variation like: 4 columns, 5 columns, 6 columns... You can get the MMC (minimum multiple common) between this 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()
来源:https://stackoverflow.com/questions/32763434/variable-number-of-columns-in-gridlayoutmanager