Skip to content

Instantly share code, notes, and snippets.

@abhimuktheeswarar
Created June 27, 2020 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhimuktheeswarar/c71eea4be53641cef39805c5ddeb0a74 to your computer and use it in GitHub Desktop.
Save abhimuktheeswarar/c71eea4be53641cef39805c5ddeb0a74 to your computer and use it in GitHub Desktop.
This decorator adds equal spacing for items in GridLayoutManager
package com.yourcompany.name
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class EqualSpaceItemDecoration(private val padding: Int) :
RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val layoutParams = view.layoutParams as GridLayoutManager.LayoutParams
val gridLayoutManager = parent.layoutManager as? GridLayoutManager
val spanSize = layoutParams.spanSize.toFloat()
val totalSpanSize = gridLayoutManager!!.spanCount.toFloat()
val n = totalSpanSize / spanSize // num columns
val c = layoutParams.spanIndex / spanSize // column index
val leftPadding = padding * ((n - c) / n)
val rightPadding = padding * ((c + 1) / n)
outRect.left = leftPadding.toInt()
outRect.right = rightPadding.toInt()
outRect.bottom = padding
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment