Android add/replace Items within RecyclerView

前端 未结 2 596
庸人自扰
庸人自扰 2021-01-20 18:20

I know there are lots of threads already on this topic, but none of the given solutions worked for me so far. I\'m trying to add or update an item of a RecyclerView

相关标签:
2条回答
  • 2021-01-20 18:55

    Use

     mItems.set(position, newItem);
    

    instead of

     mItems.add(position, newItem);
    

    because .set method will replace your data to particular position.

    0 讨论(0)
  • 2021-01-20 19:07

    This should work:

    private ArrayList<Item> mItems;
    
    public void replaceItem(final Item newItem, final int position) {
        mItems.set(position, newItem);
        notifyItemChanged(position);
    }  
    

    ArrayList.set() is the way to go to replace items.

    For adding items, just append them to mItems and then go notifyDatasetChanged(). Another way to go is to use notifyItemRangeInserted(). Depending on where/how are you adding new items and how many of them, it might be worth it.

    0 讨论(0)
提交回复
热议问题