问题描述
我将 recycleView
与 StaggeredGridLayoutManager
一起使用(列数为 3)。我需要确定当前单元格位于哪一列(按位置)。是否有可能做到这一点?请帮我。
注意:我的单元格的高度不同(正方形或矩形)
解决方法
- 要从位置获取列:您可以使用 位置的余数/模数乘以 3。
- 要从位置获取行:您可以将其除以 3。
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8
9 | 10 | 11
12 | 13 | 14
15 | 16 | 17
18 | 19 | 20
示例
for (int position = 0; position <= 20; position++) {
Log.d("LOG_TAG","Item: " + position + " In Row: " + position / 3 + " In Col: " + position % 3);
}
日志:
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 0 In Row: 0 In Col: 0
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 1 In Row: 0 In Col: 1
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 2 In Row: 0 In Col: 2
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 3 In Row: 1 In Col: 0
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 4 In Row: 1 In Col: 1
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 5 In Row: 1 In Col: 2
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 6 In Row: 2 In Col: 0
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 7 In Row: 2 In Col: 1
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 8 In Row: 2 In Col: 2
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 9 In Row: 3 In Col: 0
2021-04-21 00:33:41.634 14288-14288/.. D/LOG_TAG: Item: 10 In Row: 3 In Col: 1
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 11 In Row: 3 In Col: 2
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 12 In Row: 4 In Col: 0
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 13 In Row: 4 In Col: 1
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 14 In Row: 4 In Col: 2
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 15 In Row: 5 In Col: 0
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 16 In Row: 5 In Col: 1
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 17 In Row: 5 In Col: 2
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 18 In Row: 6 In Col: 0
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 19 In Row: 6 In Col: 1
2021-04-21 00:33:41.635 14288-14288/.. D/LOG_TAG: Item: 20 In Row: 6 In Col: 2