'RecyclerView update multiple locations

The notifyItemChanged method can only update one location at a time,and The notifyItemRangeChanged method can only update consecutive positions,How can I update multiple separate locations at once?



Solution 1:[1]

There is a really useful recyclerView item update blog here. Check it and use appropriate solution for your scenario. https://medium.com/@suragch/updating-data-in-an-android-recyclerview-842e56adbfd8

Solution 2:[2]

You can use notifyItemRangeChange when updating the data from and to in the position adapter

This example shows how to use it:

       List<String> data;
             data = new ArrayList<>();
            //Add Anything list data

             void AddMultipleItems() {

                ArrayList<String> fruits = new ArrayList<>();

                fruits.add("Apple");
                fruits.add("orange");
                fruits.add("banana");
                int fruitsIndex = 2;
                data.addAll(insertIndex, fruits );
                adapter.notifyItemRangeChanged(insertIndex, fruits.size());
            }

Use this method if you have multiple data changed but not all , those changed data also are in cluster so that you can say from 25th to 30th index data are changed .

If all data are changed call :

notifyDataSetChanged();

Notes: If you use notifyDataSetChanged(), then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged() if you are only updating a single item or a range of items.

Check out this link if you are making large or complex changes to a list.

Solution 3:[3]

In my case I had to update only two items, i.e., new and old item. I put the old items position in a variable and update both new and old positions as below,

class FontAdapter(
private var curSelectedFontSource: Int
) : ListAdapter<FontItem, FontAdapter.MyViewHolder>(Companion) {

private var oldItemPos = -1

// other implementations

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    val isSelected = getItem(position).fontSource == 
curSelectedFontSource
    if (isSelected) {
        oldItemPos = position
    }
    holder.binding.root.setOnClickListener {
        notifyItemChanged(position)
        notifyItemChanged(oldItemPos)
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Okan SerdaroÄŸlu
Solution 2 Adel B-Lahlouh
Solution 3 Ahmet B.