我想将RecyclerView SelectionTracker
选择大小限制为10个项目(最大)。
SelectionTracker初始化代码:
val selectionTracker = SelectionTracker.Builder(
"my_selection_tracker_id",
myRecyclerView,
MyItemKeyProvider(),
MyItemLookup(myRecyclerView),
StorageStrategy.createParcelableStorage(MyItemModel::class.java)
).withSelectionPredicate(SelectionPredicates.createSelectAnything())
.build()
再次阅读SelectionTracker
文档后,我发现了这个:
为了限制可以选择的项目数量,使用{@link #canSetStateForKey(Object,boolean)}和{@link #canSetStateAtPosition(int,boolean)}。
因此,我从override canSetStateForKey()
开始使用SelectionPredicate
方法并添加if条件,该条件检查项目nextState(已选择/取消选择)和已选择项目的大小。
从有关canSetStateForKey()的文档中:
@如果为{@code id}的项目可以设置为{@code nextState},则返回true
将选择大小限制为10的条件:
if(nextState && selectionTracker.selection.size() >= 10) {
return false
} else {
return true
}
完整的SelectionTracker初始化:
val selectionTracker = SelectionTracker.Builder(
"my_selection_tracker_id",
myRecyclerView,
MyItemKeyProvider(),
MyItemLookup(myRecyclerView),
StorageStrategy.createParcelableStorage(MyItemModel::class.java)
).withSelectionPredicate(object : SelectionTracker.SelectionPredicate<AttachmentMediaModel>() {
override fun canSelectMultiple(): Boolean {
return true
}
override fun canSetStateForKey(key: AttachmentMediaModel, nextState: Boolean): Boolean {
if(nextState && selectionTracker.selection.size() >= 10) { // 10 - max selection size
return false // Can't select when 10 items selected
}
return true // When selection size < 10 - allow selection
}
override fun canSetStateAtPosition(position: Int, nextState: Boolean): Boolean {
return true
}
}).build()