Skip to content

Instantly share code, notes, and snippets.

@oakkub
Created August 6, 2018 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oakkub/12b7ec7cb4f1eb3f975215c360526d0e to your computer and use it in GitHub Desktop.
Save oakkub/12b7ec7cb4f1eb3f975215c360526d0e to your computer and use it in GitHub Desktop.
package com.redplanet.tune.ui.decorations
import android.graphics.Rect
import android.support.annotation.Px
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
class GridOffsetItemDecoration(@param:Px private val spacing: Int,
private val shouldIncludeEdge: Boolean) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
super.getItemOffsets(outRect, view, parent, state)
if (parent.layoutManager !is GridLayoutManager) {
return
}
val gridLayoutManager = parent.layoutManager as GridLayoutManager
gridLayoutManager.spanSizeLookup.isSpanIndexCacheEnabled = true
val adapterPosition = parent.getChildAdapterPosition(view)
if (adapterPosition == RecyclerView.NO_POSITION) {
return
}
val spanSizeLookup = gridLayoutManager.spanSizeLookup
val spanSizeLookUpCount = spanSizeLookup.getSpanSize(adapterPosition)
val spanCount = gridLayoutManager.spanCount
val spanIndex = spanSizeLookup.getSpanIndex(adapterPosition, spanCount)
val spanGroupIndex = spanSizeLookup.getSpanGroupIndex(adapterPosition, spanCount)
val halfSpacing = (spacing / 2f).toInt()
val firstItemOfRow = spanIndex == 0
val firstRow = spanGroupIndex == 0
if (spanSizeLookUpCount == spanCount) {
if (shouldIncludeEdge) {
outRect.left = spacing
outRect.top = if (firstItemOfRow) spacing else 0
outRect.right = spacing
outRect.bottom = spacing
} else {
outRect.top = if (firstRow) 0 else halfSpacing
}
} else {
if (shouldIncludeEdge) {
outRect.left = if (firstItemOfRow) spacing else halfSpacing
outRect.top = if (firstRow) spacing else 0
outRect.right = if (firstItemOfRow) halfSpacing else spacing
outRect.bottom = spacing
} else {
val lastItemOfRow = spanIndex == spanCount - 1
outRect.left = if (firstItemOfRow) 0 else halfSpacing
outRect.right = if (lastItemOfRow) 0 else halfSpacing
outRect.top = if (firstRow) 0 else spacing
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment