1

我使用recycleViewwith StaggeredGridLayoutManager(列数为 3)。我需要确定当前单元格位于哪一列(按位置)。是否有可能做到这一点?请帮我。注意:我的单元格的高度不同(正方形或矩形)

4

2 回答 2

0
  • 要从该位置获取Column:您可以使用该位置的余数/模数 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
于 2021-04-20T22:25:34.360 回答
0

我认为您可以使用LayoutParams子视图的 来确定跨度索引。一个带有 an 的例子ItemDecoration可能看起来像这样(Kotlin):

class MyItemDecoration : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        val params = view.layoutParams as StaggeredGridLayoutManager.LayoutParams
        when(params.spanIndex) {
            0 -> outRect.apply {
                left = 20
                right = 10
            }
            1 -> outRect.apply {
                left = 10
                right = 10
            }
            2 -> outRect.apply {
                left = 10
                right = 20
            }
        }
    }
}
于 2022-02-01T13:33:02.157 回答