Last active
December 26, 2017 17:26
-
-
Save caseykulm/6caffa4dbbf9dba652f04f371345eeef to your computer and use it in GitHub Desktop.
Adds even spacing to a RecyclerView accepting a custom span count
This file contains hidden or 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(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 | |
} | |
} | |
} |
This file contains hidden or 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
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