There is recyclerview, data is loaded into it from the network. When you click on certain elements in recyclerview, new lines should be added or old lines should be deleted. In the code, the addition looks like this:

for (int i = 0; i < objectToInsert.size(); i++) { objects.add(i + position + 1, objectToInsert.get(i)); notifyItemInserted(i + position + 1); } notifyItemRangeChanged(position + 1, objects.size()); 

There is a dataset for adding objectToInsert, I’ll go through each element and add it to the main dataset for recycler view.

The position of the element is obtained as follows: in onBindViewHolder I add a teg to the view, for example, holder.objectIcon.setTag(position); and in the right place I take it:

  try { position = (Integer) view.getTag(); } catch (Exception e) { e.printStackTrace(); Log.d("NANADEVPOS", e.toString()); return; } 

Deleting rows is done similarly:

 for (int i = 0; i < objectToRemove.size(); i++) { objects.remove(position + 1); notifyItemRemoved(position + 1); } notifyItemRangeChanged(position + 1, objects.size()); 

And sometimes crashes: java.lang.IndexOutOfBoundsException: Invalid index 7, size is 5 .

If you replace the notifyItemRangeChanged method in the code with a notifyItemRangeChanged the notifyDataSetChanged do not crash and the application runs stably, but the animation for adding and deleting items disappears.

In this regard, the question is: how to add / remove an array of elements in recyclerview? Or how to save an add / remove animation when using notifyDataSetChanged

For clarity, I attach a screenshot of the list: enter image description here

A hierarchical list in which when you click on items, they collapse or unfold.

  • What behavior did you expect by adding to position + 1? - Silento
  • @Asgard I add an array of elements after a certain position. The result is a semblance of a hierarchical list. But maybe I'm wrong, explain why it is not right. - nana

1 answer 1

The solution turned out to be quite simple, as the position you need to take not the position by tag, but the position of the adapter using the getAdapterPosition() method:

int position = holder.getAdapterPosition() . The entire basic display / hide algorithm described above is correct.