This question may have been asked before, but I could not find the solution to the exact problem I am facing. I need to add a footer to my RecyclerView such that the footer scrolls with the rest of the items. I took inspiration from this article to create a FooterDecoration that adds a layout to the end of the list. https://stackoverflow.com/a/33458367
I also have DividerItemDecoration added in addition to the FooterDecoration.
The problem with this approach is that the footer is getting added before the last divider item instead of after it. How do I add the footer such that it gets added after the last item divider?
This code is in Kotlin.
class FooterDecoration(
val context: Context,
val parent: RecyclerView,
var layout: View
) : RecyclerView.ItemDecoration() {
init {
layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDraw(c, parent, state)
layout.layout(parent.left, 0, parent.right, layout.measuredHeight)
for (i in 0..parent.childCount - 1) {
val view = parent.getChildAt(i)
if (parent.getChildAdapterPosition(view) == parent.adapter.itemCount.minus(1)) {
c.save()
val top = view.bottom
c.translate(0f, top.toFloat())
layout.draw(c)
c.restore()
break
}
}
}
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
if (parent.getChildAdapterPosition(view) == parent.adapter.itemCount.minus(1)) {
outRect.set(0, 0, 0, layout.measuredHeight)
} else {
outRect.setEmpty()
}
}
}
It might be helpful to know that I am adding DividerItemDecoration before FooterDecoration.
What am I missing? Thanks for any help.
Adapter code:
class PlanCategoryAdapter(
val planNodes: List<Nodes>,
val context: Context
) : RecyclerView.Adapter<CategoryViewHolder>() {
override fun getItemCount(): Int {
return planNodes.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.view_category_item, parent, false)
return CategoryViewHolder(view)
}
override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
val searchNode = planNodes[position]
holder.bind(searchNode)
}
}
class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvTitle: TextView by bindView(R.id.tvTitle)
fun bind(planNode: Node) {
tvTitle.text = planNode.displayName
}
}