Skip to content

Instantly share code, notes, and snippets.

@caseykulm
Last active December 26, 2017 17:26
Show Gist options
  • Save caseykulm/6caffa4dbbf9dba652f04f371345eeef to your computer and use it in GitHub Desktop.
Save caseykulm/6caffa4dbbf9dba652f04f371345eeef to your computer and use it in GitHub Desktop.
Adds even spacing to a RecyclerView accepting a custom span count
class SpacesItemDecoration(private val space: Int, private val span: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
val lastPosition = parent.adapter.itemCount - 1
val bottomRow = (lastPosition - position) < span
val rightColumn = (position % span) == (span - 1)
/**
* |A----B----C|
* | |
* | |
* D I E
* | |
* | |
* |F----G----H|
*/
// All get top and left
outRect.top = space
outRect.left = space
// C & E & H
if (rightColumn) {
outRect.right = space
}
// F & G & H
if (bottomRow) {
outRect.bottom = space
}
}
}
val spaceInPixels = resources.getDimensionPixelSize(R.dimen.cell_space)
val numberOfColumns = 2
val spaceDecoration = SpacesItemDecoration(spaceInPixels, numberOfColumns)
recyclerView.addItemDecoration(spaceDecoration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment