Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adds start/end padding to first/last item of a horizontal RecyclerView (like Play Store app)
class HorizontalPaddingItemDecoration(
private val paddingStart: Int = 0,
private val paddingEnd: Int = 0
) : RecyclerView.ItemDecoration() {
private var isRtl: Boolean? = null
fun isRTL(ctx: Context): Boolean {
val config = ctx.resources.configuration
return config.layoutDirection == View.LAYOUT_DIRECTION_RTL
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
super.getItemOffsets(outRect, view, parent, state)
if (isRtl == null) {
isRtl = isRTL(view.context)
}
val position = parent.getChildAdapterPosition(view)
if (position == 0) {
if (!isRtl!!) {
outRect.left += paddingStart
} else {
outRect.right += paddingStart
}
}
if (position == parent.adapter.itemCount - 1) {
if (!isRtl!!) {
outRect.right += paddingEnd
} else {
outRect.left += paddingEnd
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment