Created
May 30, 2019 12:59
-
-
Save burkaslarry/de5d5c853278173d863480ab56eec5c6 to your computer and use it in GitHub Desktop.
Setup Equal Spacing of Grid Layout of RecyclerView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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