Gunaseelan
Gunaseelan

Reputation: 15525

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

Upvotes: 14

Views: 20040

Answers (3)

Luis Muñoz
Luis Muñoz

Reputation: 149

Here is my solution for dinamic span in this case the maximun span is 4 and 12 is multiple of 4, 3 and 2. //NUMBER OF THE SPAN THAT YOU WANT is the size of your array

val mutipleSpan = 12  //least common multiple
val maxSpan = 4//max span count 
val mLayoutManager = object : GridLayoutManager(itemView.context, mutipleSpan){}

mLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                val actualSize =  //NUMBER OF THE SPAN THAT YOU WANT
                if(actualSize< maxSpan){
                    return  mutipleSpan/actualSize
                }
                return mutipleSpan/maxSpan
            }
        }

recycler.layoutManager = mLayoutManager 

Upvotes: 1

MJ Studio
MJ Studio

Reputation: 4611

Use FlexBoxLayoutManager of library by Google.

Document describes this is a valid solution.

enter image description here

Upvotes: 0

Levi Moreira
Levi Moreira

Reputation: 12005

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

Upvotes: 28

Related Questions