Skip to content

Instantly share code, notes, and snippets.

@dadouf
Created December 11, 2020 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dadouf/38f5816447c78d020d894c5c7c0c0fae to your computer and use it in GitHub Desktop.
Save dadouf/38f5816447c78d020d894c5c7c0c0fae to your computer and use it in GitHub Desktop.
class BoundsOffsetDecoration : ItemDecoration() {
override fun getItemOffsets(outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val itemPosition = parent.getChildAdapterPosition(view)
// It is crucial to refer to layoutParams.width
// (view.width is 0 at this time)!
val itemWidth = view.layoutParams.width
val offset = (parent.width - itemWidth) / 2
if (itemPosition == 0) {
outRect.left = offset
} else if (itemPosition == state.itemCount - 1) {
outRect.right = offset
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment