Search code examples
javaandroidandroid-recyclerviewgridlayoutmanager

RecyclerView GridLayoutManager: Individual layout per item count


I need some help with my GridLayoutManager.

If I have an item it should be displayed as normal in the middle.
For two items these should be next to one another. Example with 2 Items From three to four items it should be displayed like a square. Example with 3 Items Example with 4 Items

If I'm right, this should be the case with spanCount 2. But that with the 5 items (so three in a row) is then problematic

From five items (and up) should each be 3 in a row Example with 5 Items It would be especially good if the items in the bottom row were also in the middle



I hope someone can help me and thanks in advance


Solution

  • You can set your span dynamically by subclassing GridLayoutManager like this :

    class CustomGridLayoutManager(context: Context) : GridLayoutManager(context, 2) {
    
        override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
            updateSpanCount()
            super.onLayoutChildren(recycler, state)
        }
    
        private fun updateSpanCount() {
            val colCount = if (childCount <= 4) {
                2
            } else {
                3
            }
            this.spanCount = colCount
        }
    }
    

    If you want to center your elements in the last row, it would a little convoluted to do it through GridLayoutManager. You might want to check FlexboxLayout for that purpose. It's a library made by Google itself and has flex box model found commonly in HTML5 / CSS world.