问题
I am using SelectionTracker to implement a multiple selection RecyclerView. the select/unselect feature works as expected if I do it manually (Item is on the screen and I change its state by tapping) but if I try to unselect all items, some of which are off screen, using clearSelection method of selection tracker it only unselects the items which are currently visible on the screen.
This is how I am building the SelectionTracker
tracker = SelectionTracker.Builder<Long>(
"mySelection",
recyclerView,
MyKeyProvider(recyclerView),
MyItemDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(
SelectionPredicates.createSelectAnything()
).build()
recyclerAdapter.tracker = tracker
Following is bindItem and onBindViewHolder methods of ViewHolder and adapter respectively
fun bindItems(model: Model, isActivated: Boolean) {
itemView.isActivated = isActivated
if(itemView.isActivated){
/* Make item selected. (make background dark) */
}
else{
/* Make item unselected. (Apply original background) */
}
}
}
override fun onBindViewHolder(holder: RecyclerAdapter.ViewHolder, position: Int) {
val number = displayList[position]
tracker?.let {
holder.bindItems(number, it.isSelected(position.toLong()))
}
}
I call the clear selection method on click of a menu item
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if((selectionMode) && (item?.itemId==android.R.id.home)){
tracker.clearSelection()
}
return super.onOptionsItemSelected(item)
}
回答1:
You add a listener to the tracker, which when changing the state of any element, checks if it was the last selected element and updates the entire list if this is true
tracker?.addObserver(object : SelectionTracker.SelectionObserver<Long>() {
override fun onItemStateChanged(key: Long, selected: Boolean) {
if(!tracker!!.hasSelection())
adapter.notifyDataSetChanged()
super.onItemStateChanged(key, !selected)
}
})
来源:https://stackoverflow.com/questions/56585352/how-to-unselect-all-selected-items-in-recyclerviews-selectiontracker-even-if-so