How to unselect all selected items in RecyclerView's SelectionTracker even if some items are scrolled off the screen?

爷,独闯天下 提交于 2020-06-26 08:31:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!