我正在使用SelectionTracker实施多选RecyclerView。如果我手动执行选择/取消选择功能,则按预期方式可以正常工作(项目在屏幕上,并且通过轻击来更改其状态),但是如果我尝试取消选择所有项目,其中一些不在屏幕上,请使用选择跟踪器的clearSelection方法仅取消选择屏幕上当前可见的项目。
这就是我构建SelectionTracker的方式
tracker = SelectionTracker.Builder<Long>(
"mySelection",
recyclerView,
MyKeyProvider(recyclerView),
MyItemDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(
SelectionPredicates.createSelectAnything()
).build()
recyclerAdapter.tracker = tracker
以下分别是ViewHolder和适配器的bindItem和onBindViewHolder方法
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()))
}
}
[我单击菜单项时就调用清除选择方法
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if((selectionMode) && (item?.itemId==android.R.id.home)){
tracker.clearSelection()
}
return super.onOptionsItemSelected(item)
}
您向跟踪器添加了一个侦听器,当更改任何元素的状态时,它会检查它是否是最后选择的元素,如果是,则更新整个列表。
tracker?.addObserver(object : SelectionTracker.SelectionObserver<Long>() {
override fun onItemStateChanged(key: Long, selected: Boolean) {
if(!tracker!!.hasSelection())
adapter.notifyDataSetChanged()
super.onItemStateChanged(key, !selected)
}
})