【问题标题】:recycler view item decoration, getItemOffsets is only called on the last added itemrecyclerview itemdecoration, getItemOffsets 只在最后添加的item上调用
【发布时间】:2019-05-23 14:00:16
【问题描述】:

我的回收站视图中附加了一个物品装饰。它应该仅在最后一项上添加大量填充。这工作正常。但是,当我添加新项目时,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;
    }
}

【问题讨论】:

  • 您正在添加一个项目,但您想重新绘制所有项目。因此,尝试用 notifyDataSetChanged() 替换 notifyItemInserted()。这将重新绘制所有项目。
  • @W0rmH0le 使用 notifyDataSetChanged 丢失动画

标签: android android-recyclerview item-decoration


【解决方案1】:

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);
    }
}

另外,正如您所提到的,您应该在getItemOffsets() 期间使用state.getItemCount() 而不是parent.getChildAdapterPosition(view)

【讨论】:

  • hmm 都试过了(我猜第二个解决方案更接近我所追求的),但都没有工作
  • 所以这非常有帮助,谢谢,但是这条线 outRect.left += mHorizo​​ntalSpace;不需要并且有奇怪的副作用,这也会在轮换时死掉,我会尝试扩展它并接受你的回答,非常感谢
  • 好的,这个问题的实际答案是使用 state.getItemCount() ,非常感谢,如果没有你,我不会解决它
【解决方案2】:

我需要使用 state.getItemCount() 而不是 parent.getChildCount()

【讨论】:

    【解决方案3】:

    在插入数据之前尝试调用 RecyclerView.invalidateItemDecorations()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      相关资源
      最近更新 更多