android - 回收器视图项目装饰,getItemOffsets 仅在最后添加的项目上调用
问题描述
我的回收站视图附加了一个物品装饰。它应该仅在最后一项上添加大量填充。这工作正常。但是,当我添加新项目时,getItemOffsets
仅对最后一个项目(而不是回收站视图中的每个项目)调用。这样,我最终在每个项目上都有这么大的填充。
添加新视图时,如何删除其余视图上的正确填充?我想以正确的方式添加项目以保留动画
public void onItemInserted(Card card, int position){
cardList.add(card);
notifyItemInserted(getItemCount() -1);
}
我的项目偏移方法:
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.top = horizontalSpace;
outRect.bottom = horizontalSpace;
outRect.left = horizontalSpace;
outRect.right = 0;
if (parent.getChildAdapterPosition(view) == parent.getChildCount() - 1){
outRect.right = endSpace;
}
}
解决方案
getItemOffsets()
仅对最后一项调用。因此,旧物品的装饰永远不会被重新存储。发生这种情况是因为您调用了:notifyItemInserted(getItemCount() -1);
为了调用getItemOffsets()
最后两项,您必须:
public void onItemInserted(){
items++;
int lastPosition = getItemCount() - 1;
if(lastPosition > 0) {
// Request to redraw last two items. So, new item will receive proper padding and old item will restore to the default position
notifyItemRangeChanged(lastPosition - 1, lastPosition);
} else {
notifyItemChanged(lastPosition);
}
}
此外,正如您自己所提到的,您应该使用state.getItemCount()
而不是parent.getChildAdapterPosition(view)
在getItemOffsets()
推荐阅读
- python - 双向转换时代
- python - 如何在django测试框架中模拟两个并行请求
- timer - 线程组迭代之间的 Jmeter Pacing
- command-line-arguments - nodemon 传递位于执行文件之后的参数
- ios - 在 iOS 中使用 LinkedIn + firebase auth + Flutter 登录
- java - 实体类在使用@IdClass 时扩展它自己的 PK 类
- wordpress - Wordpress 插件翻译:load_plugin_textdomain 不会从插件语言文件夹中加载 .mo 文件,只能从全局语言文件夹中加载
- r - 使用对象选择 dplyr 中的列
- c# - Visual Studio 2019 中的解决方案显示 0 个项目
- openlayers - 在qgis2web中发布意大利土地注册WMS服务