I\'m building a shopping cart RecyclerView that displays all the items in the cart in a RecyclerView, as well as it has an additional view at the bottom that summarizes the cart
Building upon Lamorak's answer I've rewritten the code in Kotlin and altered it to accommodate for RecyclerView paddings and item margins:
class LastSticksToBottomItemDecoration: RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
parent.adapter?.itemCount?.let { childCount ->
if (parent.getChildLayoutPosition(view) != childCount - 1) return
val lastViewBottom = when (childCount) {
1 -> 0
else -> parent.layoutManager?.findViewByPosition(childCount - 2)?.let {
calculateViewBottom(it, parent)
} ?: 0
}
view.measure(parent.width, parent.height)
max(
0,
parent.height -
parent.paddingTop -
parent.paddingBottom -
lastViewBottom -
view.measuredHeight -
view.marginTop -
view.marginBottom
).let { topOffset ->
outRect.set(0, topOffset, 0, 0)
}
}
}
private fun calculateViewBottom(view: View, parent: RecyclerView): Int =
(view.layoutParams as ViewGroup.MarginLayoutParams).let {
view.measure(parent.width, parent.height)
view.y.toInt() + view.measuredHeight + it.topMargin + it.bottomMargin
}
}