-
-
Save iosandroiddev/98cd695b07488defdaeaa9bdd0a83d5c to your computer and use it in GitHub Desktop.
This file contains 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
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