Skip to content

Instantly share code, notes, and snippets.

@Zulqurnain
Created November 10, 2022 00:31
Show Gist options
  • Save Zulqurnain/2133b97f8816693518fe4dd9845acc13 to your computer and use it in GitHub Desktop.
Save Zulqurnain/2133b97f8816693518fe4dd9845acc13 to your computer and use it in GitHub Desktop.
GridLayoutManager used in RecyclerView , then use this Item Decoration for spacing
class GridSpacingItemDecoration(
private val spanCount: Int,
private val spacing: Int,
private val includeEdges: Boolean
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
val position: Int = parent.getChildAdapterPosition(view)
val column = position % spanCount
if (includeEdges) {
outRect.left = spacing - column * spacing / spanCount
outRect.right = (column + 1) * spacing / spanCount
if (position < spanCount) {
outRect.top = spacing
}
outRect.bottom = spacing
} else {
outRect.left = column * spacing / spanCount
outRect.right = spacing - (column + 1) * spacing / spanCount
if (position >= spanCount) {
outRect.top = spacing
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment