RecyclerView的GridLayoutManager动态跨度计数 [英] RecyclerView's GridLayoutManager dynamic span count

查看:388
本文介绍了RecyclerView的GridLayoutManager动态跨度计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码动态更改跨度计数.

I am using following code dynamically change span count.

val layoutManager = GridLayoutManager(this, 3)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        when (position) {
            0, 1, 2 -> return 1
            3, 4 -> return 2
            5 -> return 3
            else -> return 1
        }
    }
}

我得到以下输出. 但我希望 D和E 在水平方向上对齐.我不怎么做.

And I got following output. But I want D and E should horizontally equally aligned. I don't how to do it.

实际上我在适配器中有3种类型, HEADER,TYPE_A,TYPE_B . HEADER 应该只有一行,而 TYPE_A 是3行, TYPE_B 是2行.

Actually I have 3 types in adapter, HEADER, TYPE_A, TYPE_B. HEADER should have only one row, and TYPE_A is 3 rows, TYPE_B is 2 rows.

因此,请问我可以帮助使某些列具有1个1行,而某些列仅具有2行(水平均等对齐),而另一些具有3行.

So may I get help to make some columns should have one 1 row, and some have only 2 rows(horizontally equally aligned) and some have 3 rows.

推荐答案

在这种情况下,您应该使网格布局具有3个以上的单元格.您需要选择一个对所有三种类型的单元格都适用的数字,最好是6,因为按行有3个单元格会返回2.要按行有2个单元格,您会返回3并具有每行1个单元格,您将返回6:

In that case you should make your grid layout have more than 3 cells. You'd need to pick a number that works for all three types of cells, a 6 is good because to have 3 cells by row you'd return a 2. To have 2 cells by row you'd return a 3 and to have 1 cell by row you'd return a 6:

val layoutManager = GridLayoutManager(this, 6)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        when (position) {
            0, 1, 2 -> return 2
            3, 4 -> return 3
            5 -> return 6
            else -> return 2
        }
    }
}

这篇关于RecyclerView的GridLayoutManager动态跨度计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆