Skip to content

Instantly share code, notes, and snippets.

@momvart
Last active August 19, 2020 10:37
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 momvart/08dd0b18b6c7e4ae6d351a1b6e1e6e49 to your computer and use it in GitHub Desktop.
Save momvart/08dd0b18b6c7e4ae6d351a1b6e1e6e49 to your computer and use it in GitHub Desktop.
An item decoration for recyclerview which adds margin between items.
import android.content.Context
import android.graphics.Rect
import android.util.LayoutDirection
import android.view.View
import androidx.annotation.DimenRes
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MarginItemDecoration(
private val marginLeft: Int,
private val marginTop: Int,
private val marginRight: Int,
private val marginBottom: Int
) : RecyclerView.ItemDecoration() {
companion object {
fun all(context: Context, @DimenRes resId: Int): MarginItemDecoration {
val margin = context.resources.getDimensionPixelSize(resId)
return MarginItemDecoration(margin, margin, margin, margin)
}
fun bottom(context: Context, @DimenRes resId: Int): MarginItemDecoration {
val margin = context.resources.getDimensionPixelSize(resId)
return MarginItemDecoration(0, 0, 0, margin)
}
}
override fun getItemOffsets(
outRect: Rect, view: View,
parent: RecyclerView, state: RecyclerView.State
) {
with(outRect) {
left = marginLeft
top = marginTop
right = marginRight
bottom = marginBottom
}
}
}
class MarginGridItemDecoration(private val margin: Int) : RecyclerView.ItemDecoration() {
private val halfMargin = margin / 2
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
outRect.bottom = margin
val colCount = (parent.layoutManager as GridLayoutManager).spanCount
val (colIndex, colSize) = (view.layoutParams as GridLayoutManager.LayoutParams).run { spanIndex to spanSize }
val isRtl = parent.layoutDirection == LayoutDirection.RTL
if (colIndex == 0) //First column
outRect.setStart(isRtl, margin)
else //colIndex > 0 //Middle
outRect.setStart(isRtl, halfMargin)
if (colIndex + colSize == colCount) //Last column
outRect.setEnd(isRtl, margin)
else //colIndex + colSize < colCount //Middle
outRect.setEnd(isRtl, halfMargin)
}
}
fun Rect.setStart(isRtl: Boolean, start: Int) =
if (!isRtl) left = start
else right = start
fun Rect.setEnd(isRtl: Boolean, end: Int) =
if (!isRtl) right = end
else left = end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment