Make last Item / ViewHolder in RecyclerView fill rest of the screen or have a min height
You can find the remaining space in RecyclerView after laying out the last item and add that remaining space to the minHeight
of the last item.
val isLastItem = getItemCount() - 1 == position
if (isLastItem) {
val lastItemView = holder.itemView
lastItemView.doOnLayout {
val recyclerViewHeight = recyclerView.height
val lastItemBottom = lastItemView.bottom
val heightDifference = recyclerViewHeight - lastItemBottom
if (heightDifference > 0) {
lastItemView.minimumHeight = lastItemView.height + heightDifference
}
}
}
In onBindHolder
check if the item is last item using getItemCount() - 1 == position
. If it is the last item, find the height difference by subtracting recyclerView height with lastItem bottom (getBottom()
gives you the bottom most pixel of the view relative to it's parent. In this case, our parent is RecyclerView
).
If the difference is greater than 0, then add that to the current height of the last view and set it as minHeight
. We are setting this as minHeight
instead of setting directly as height
to support dynamic content change for the last view.
Note: This code is Kotlin, and doOnLayout function is from Android KTx. Also your RecyclerView
height should be match_parent
for this to work (I guess that's obvious).