Skip to content

Instantly share code, notes, and snippets.

@sevar83
Created February 20, 2017 08:02
Show Gist options
  • Save sevar83/1172423f265e1cbb7a04f3d22b12021a to your computer and use it in GitHub Desktop.
Save sevar83/1172423f265e1cbb7a04f3d22b12021a to your computer and use it in GitHub Desktop.
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
}
}
}
}
@iosandroiddev
Copy link

RecyclerView's adapter can be null. Just suggesting

parent.adapter?.let {
            if (position == it.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