'How to select all items listed in Recyclerview using androidx.recyclerview.selection?

I am using androidx.recyclerview.selection for selecting items in a RecyclerView. I am trying to build an edit fragment in which it pre-populates the old views in the RecyclerView. At present, I was able to load the old values from API call and update the adapter's list by notifyDataSetChanged call. But I want all the items in list to be selected in other words I want to add all items somehow to SelectionTracker object somehow while the fragment loads.

Whenever notifyDataSetChanged is called I could see SelectionTracker's observer onSelectionRefresh() is triggered but I couldn't update the selection tracker there since it is going on infinite call loop.



Solution 1:[1]

SelectionTracker.setItemsSelected:

selectionTracker?.setItemsSelected(listOfKeysToBeSelected, true)

Solution 2:[2]

val size = documents.size
for(number in 0 until size){
   (tracker as SelectionTracker<Long>?)?.select(number.toLong())
}

pass all position of recyclerview using for loop start with 0 to total count of single item.

Solution 3:[3]

You select every item in the RecyclerView adapter by iteration.

Assuming your key is Long:

for (i in 0 until recyclerAdapter.itemCount)
    selectionTracker.select(i.toLong()) 

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 khoben
Solution 2
Solution 3