RecyclerView's GridLayoutManager dynamic span count

谁说我不能喝 提交于 2020-08-22 11:56:15

问题


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
        }
    }
}

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

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.

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.


回答1:


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
        }
    }
}


来源:https://stackoverflow.com/questions/51244151/recyclerviews-gridlayoutmanager-dynamic-span-count

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