Skip to main content

Dynamic Grid Count in GridLayoutManager using RecyclerView | Android | Kotlin

Sometime we need RecyclerView filled with dynamic row count. For example, some row has 3 columns, and some has 2 columns, and some should have only one column like that.
Here is the simple example of dynamic grid count using GridLayoutManager in RecyclerView.
val layoutManager = GridLayoutManager(this, 6)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        when (position) {
            0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20 -> return 2
            3, 4, 9, 10, 15, 16, 21, 22, 24, 25 -> return 3
            5, 11, 17, 23 -> return 6
            else -> return 2
        }
    }
}
recyclerView.layoutManager = layoutManager
Screenshot:

Interesting right?

If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.

Thank You


Comments

Post a Comment