recycler 查看项目装饰,getItemOffsets 仅在最后添加的项目上调用
recycler view item decoration, getItemOffsets is only called on the last added item
我的回收站视图附有物品装饰。它应该只在最后一项上添加大量填充。这很好用。但是,当我添加新项目时,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()
仅针对最后一项调用。所以,旧物品的装饰永远不会 re-stored。发生这种情况是因为您调用了: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);
}
}
此外,正如您自己提到的,您应该在 getItemOffsets()
期间使用 state.getItemCount()
而不是 parent.getChildAdapterPosition(view)
我需要使用 state.getItemCount() 而不是 parent.getChildCount()
尝试在插入数据之前调用 RecyclerView.invalidateItemDecorations()。
我的回收站视图附有物品装饰。它应该只在最后一项上添加大量填充。这很好用。但是,当我添加新项目时,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()
仅针对最后一项调用。所以,旧物品的装饰永远不会 re-stored。发生这种情况是因为您调用了: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);
}
}
此外,正如您自己提到的,您应该在 getItemOffsets()
state.getItemCount()
而不是 parent.getChildAdapterPosition(view)
我需要使用 state.getItemCount() 而不是 parent.getChildCount()
尝试在插入数据之前调用 RecyclerView.invalidateItemDecorations()。