首页 > 解决方案 > ItemDecoration 底部间距在添加新项目时未更新

问题描述

我的 recyclerview 有一个 SpacingDecoration,它将在列表中的最后一项之后添加一些额外的间距。

这是我的间距装饰

    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()

    }

}

这很好用。

但是当在列表底部添加一个新项目时,问题就开始了。

我正在使用 DiffUtils 来更新列表。

当列表更新并向列表添加新项目时,它会在底部间距 70 Dp 之后添加新项目。

希望你能理解我的问题。

我想添加最后一个新项目,以便最后一个项目和它之前的项目之间的间距减少到十二Dp。

请帮忙,因为我只是一个初学者

标签: android-recyclerviewandroid-diffutilsitem-decoration

解决方案


我发现这个答案有帮助:https ://stackoverflow.com/a/62002161/9901599

基本上,RecyclerView.invalidateItemDecorations()一旦你刷新了你的数据就打电话。由于我使用的是 ListAdapter,我发现我必须在列表实际更新后将此行放入回调中,如下所示:

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

推荐阅读