我的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。
由于我只是一个初学者,请提供帮助
答案 0 :(得分:1)
我发现此答案有所帮助:https://stackoverflow.com/a/62002161/9901599
基本上,刷新数据后,请致电RecyclerView.invalidateItemDecorations()
。由于我使用的是ListAdapter,因此我发现必须在列表实际更新后将这一行放入回调中,如下所示:
myAdapter.submitList(newList) {
// this callback runs when the list is updated
myRecyclerView.invalidateItemDecorations()
}