Skip to content

Instantly share code, notes, and snippets.

@silmood
Last active November 15, 2018 07:18
Show Gist options
  • Select an option

  • Save silmood/92f0607d8713b5c92cc3949c750a8a55 to your computer and use it in GitHub Desktop.

Select an option

Save silmood/92f0607d8713b5c92cc3949c750a8a55 to your computer and use it in GitHub Desktop.
ItemOffsetDecorator
class ItemOffsetDecoration(@DimenRes val offsetId: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val offset = view.context.resources.getDimensionPixelSize(offsetId)
val position = parent.getChildAdapterPosition(view)
val items = parent.adapter?.itemCount ?: 0
if (parent.layoutManager is GridLayoutManager) {
val columns = (parent.layoutManager as GridLayoutManager).spanCount
val rows = (items / columns)
val column = getColumn(position, columns)
val row = getRow(position, columns)
val topOffset = if (row == 1) offset else offset / 2
val leftOffset = if (column == 1) offset else offset / 2
val bottomOffset = if (row == rows) offset else offset / 2
val rightOffset = if (column == columns) offset else offset / 2
outRect.set(leftOffset, topOffset, rightOffset, bottomOffset)
} else if (parent.layoutManager is LinearLayoutManager) {
val top = if (position > 0) 0 else offset
outRect.set(offset, top, offset, offset)
}
}
private fun getRow(position: Int, columns: Int) =
Math.ceil((position.toDouble() + 1.0) / columns.toDouble()).toInt()
private fun getColumn(position: Int, columns: Int) = (position % columns) + 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment