Is it possible to have the last item in a RecyclerView to be docked to the bottom if there is no need to scroll?

后端 未结 4 1183
日久生厌
日久生厌 2021-02-08 17:35

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

4条回答
  •  逝去的感伤
    2021-02-08 17:58

    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
            }
    }
    

提交回复
热议问题