Skip to content

Instantly share code, notes, and snippets.

@sidthakkar12
Last active August 10, 2020 13:17
Show Gist options
  • Save sidthakkar12/27eae88fdf03bee201d96cc0bfe6cc70 to your computer and use it in GitHub Desktop.
Save sidthakkar12/27eae88fdf03bee201d96cc0bfe6cc70 to your computer and use it in GitHub Desktop.
Here's my custom class that allows equal spacing between grid cells in Kotlin:
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
class GridItemOffsetDecoration(private val spanCount: Int, private var mItemOffset: Int) : ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
if (position < spanCount) {
if (position % 2 == 0) { // left grid
outRect.set(0, mItemOffset, mItemOffset / 2, mItemOffset / 2)
} else { // right grid
outRect.set(mItemOffset / 2, mItemOffset, 0, mItemOffset / 2)
}
} else if (position % 2 == 0) { // left grid
outRect.set(0, mItemOffset / 2, mItemOffset, mItemOffset / 2)
} else if (position % 2 == 1) { // right grid
outRect.set(mItemOffset / 2, mItemOffset / 2, 0, mItemOffset / 2)
} else {
if (position % 2 == 0) { // left grid
outRect.set(0, mItemOffset / 2, mItemOffset, mItemOffset)
} else { // right grid
outRect.set(mItemOffset / 2, mItemOffset / 2, 0, mItemOffset)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment