RecyclerView --SelectionTracker 将选择大小限制为 10 个项目

RecyclerView --SelectionTracker limit selection size to 10 items

我想将我的 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 文档后,我找到了这个:

In order to limit the number of items that can be selected,
use {@link #canSetStateForKey(Object, boolean)} and
{@link #canSetStateAtPosition(int, boolean)}.

所以,我 override canSetStateForKey() 方法来自 SelectionPredicate
并添加 if 条件来检查项目 nextState (selected/deselected) 和 selected items size.

来自关于 canSetStateForKey() 的文档:

@return true if the item at {@code id} can be set to {@code nextState}

将选择大小限制为 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()

我用过这个,但我改变了一点,跟踪器将取消选择最旧的选择,以便为新选择“腾出空间”。类似(我的是 java,我只使用 long 键)

@Override
public boolean canSetStateForKey(@NonNull Long key, boolean nextState) {
    if (nextState && tracker.getSelection().size() >= MAX_SELECTIONS) {
        // Deselect the first selection and return true to allow the new item to be selected
        tracker.deselect(tracker.getSelection().iterator().next());
    }
    return true;

}