Created
February 20, 2017 08:02
-
-
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)
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
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
RecyclerView's adapter can be null. Just suggesting