android-recyclerview - 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。
请帮忙,因为我只是一个初学者
解决方案
我发现这个答案有帮助:https ://stackoverflow.com/a/62002161/9901599
基本上,RecyclerView.invalidateItemDecorations()
一旦你刷新了你的数据就打电话。由于我使用的是 ListAdapter,我发现我必须在列表实际更新后将此行放入回调中,如下所示:
myAdapter.submitList(newList) {
// this callback runs when the list is updated
myRecyclerView.invalidateItemDecorations()
}
推荐阅读
- python - 如何使用 Flask 接收 excel 文件作为输入并使用 openpyxl 读取它?
- git - Git pre-commit/pre-push hook 在提交时运行单元测试,在工作树上进行未提交的更改
- c++ - 你能用参数制作一个函数向量吗?
- node.js - 如何通过 parse / back4app 使用会话?
- ios - 什么是 AuthStateDidChangeListenerHandle?
- mysql - 打开有密码的连接:运行时错误'-2147221241(80040107)自动化错误未指定错误
- python - NumPy histogram2d 具有旋转的非正交分箱网格
- android - 即使在正确设置 abiFilters 之后,Android Studio 也会忽略 ndk-build 的 APP_ABI
- c# - Xamarin.forms socket.io 客户端
- apache-zookeeper - Apache Ignite Cluster 在网络分段情况下具有 ZooKeeper 发现行为