Skip to content

Instantly share code, notes, and snippets.

@burkaslarry
Created May 30, 2019 12:59
Show Gist options
  • Save burkaslarry/de5d5c853278173d863480ab56eec5c6 to your computer and use it in GitHub Desktop.
Save burkaslarry/de5d5c853278173d863480ab56eec5c6 to your computer and use it in GitHub Desktop.
Setup Equal Spacing of Grid Layout of RecyclerView
class SpacesItemDecoration (): RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State
) {
val requiredSpacing = 32
val position = parent.getChildViewHolder(view).adapterPosition
val itemCount = state.itemCount
val layoutManager = parent.layoutManager
if (layoutManager is GridLayoutManager) {
val gridLayoutManager = layoutManager
val cols = gridLayoutManager.spanCount
if(position % cols == 0 ) { //left most item
outRect.left = 0
outRect.top = requiredSpacing / 2
outRect.bottom = requiredSpacing / 2
outRect.right = requiredSpacing / 2
}else if(position % cols == cols -1 ) {
outRect.left = requiredSpacing / 2
outRect.top = requiredSpacing / 2
outRect.bottom = requiredSpacing / 2
outRect.right = 0
}else{
outRect.left = requiredSpacing / 2
outRect.top = requiredSpacing / 2
outRect.bottom = requiredSpacing / 2
outRect.right = requiredSpacing / 2
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment