Sundaravel
Sundaravel

Reputation: 494

ItemDecoration bottom spacing not updating on adding a new Item

I have a SpacingDecoration for my recyclerview which will add some extra spacing after the last item in the list.

Here is my Spacing Decoration

    class SpacingDecoration(val context:Context):RecyclerView.ItemDecoration() {

    private val twelveDp=getPixelValue(12)
    private val seventyDp=getPixelValue(70)

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val dataCount=parent.adapter!!.itemCount
        val viewPosition=parent.getChildAdapterPosition(view)

        outRect.left=twelveDp
        outRect.right=twelveDp

        when(viewPosition){
            0->{
                outRect.top=twelveDp
                outRect.bottom=twelveDp/2
                return
            }

            dataCount-1 ->{
                outRect.top=twelveDp/2
                outRect.bottom=seventyDp
                return
            }

            else->{
                outRect.top=twelveDp/2
                outRect.bottom=twelveDp/2
            }
        }


    }

    private fun getPixelValue(Dp: Int): Int {

        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            Dp.toFloat(),
            context.resources.displayMetrics
        ).toInt()

    }

}

This works nicely.

But the problem starts when a new item is added at the bottom of the list.

I am using DiffUtils to update the list.

When the list updates and adds a new item to the list, it adds the new item after the bottom spacing of seventy Dp.

Hope u understand my problem.

I want to add the last new item so that the spacing between the last item and the item before it reduces to twelveDp.

Please help as I am just a beginner

Upvotes: 1

Views: 1476

Answers (1)

machfour
machfour

Reputation: 2709

I found this answer helped: https://stackoverflow.com/a/62002161/9901599

Basically, call RecyclerView.invalidateItemDecorations() once you have refreshed your data. Since I was using ListAdapter, I found that I had to put this line in the callback after the list actually updates, like this:

myAdapter.submitList(newList) {
    // this callback runs when the list is updated
    myRecyclerView.invalidateItemDecorations()
}

Upvotes: 4

Related Questions