Home » Android » android – notifyItemInserted() not working as I was expecting

android – notifyItemInserted() not working as I was expecting

Posted by: admin June 15, 2020 Leave a comment

Questions:

What I need to do is inserting item to the top of RecyclerView. I have adapter which persists List of my items and when I want to add to the top of RecyclerView I’m simply using this code:

mItems.add(0, item);
notifyItemInserted(0)

Unfortunately it’s just reloading last item of RecyclerView. Of course when I change notifyItemInserted to notifyDataSetChanged() everything works fine. Why is notifyItemInserted not appropriate?

How to&Answers:

Just remove setHasFixedSize(true) from your initialization of RecyclerView.

Answer:

mItems.add(0, item);

if(mItems.size()==1){

   notifyDataSetChanged();
} else {

notifyItemInserted(position);

}

Answer:

You are using this.

mItems.add(0, item);
notifyItemInserted(0)

You should use this.

mItems.add(item);
notifyItemInserted(0)

Then, only it will work as in first case, you are replacing 0th index item with item, whereas in 2nd scenario an item is being pushed at top i.e at 0th position.