androidandroid-recyclerviewgridlayoutmanager

RecyclerView's GridLayoutManager dynamic span count


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.

enter image description here


Solution

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