Variable number of columns in GridLayoutManager

痞子三分冷 提交于 2019-12-12 07:47:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!