ItemKeyProvider.java revision f27b1ffc67228d73326ec3426fef4c9db75cd6fd
1/*
2 * Copyright 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package androidx.recyclerview.selection;
18
19import static android.support.v4.util.Preconditions.checkArgument;
20
21import android.support.annotation.IntDef;
22import android.support.annotation.NonNull;
23import android.support.annotation.Nullable;
24
25import java.lang.annotation.Retention;
26import java.lang.annotation.RetentionPolicy;
27
28/**
29 * Provides selection library access to stable selection keys identifying items
30 * presented by a {@link android.support.v7.widget.RecyclerView RecyclerView} instance.
31 *
32 * @param <K> Selection key type. @see {@link StorageStrategy} for supported types.
33 */
34public abstract class ItemKeyProvider<K> {
35
36    /**
37     * Provides access to all data, regardless of whether it is bound to a view or not.
38     * Key providers with this access type enjoy support for enhanced features like:
39     * SHIFT+click range selection, and band selection.
40     */
41    public static final int SCOPE_MAPPED = 0;
42
43    /**
44     * Provides access to cached data based for items that were recently bound in the view.
45     * Employing this provider will result in a reduced feature-set, as some
46     * features like SHIFT+click range selection and band selection are dependent
47     * on mapped access.
48     */
49    public static final int SCOPE_CACHED = 1;
50
51    @IntDef({
52            SCOPE_MAPPED,
53            SCOPE_CACHED
54    })
55    @Retention(RetentionPolicy.SOURCE)
56    public @interface Scope {}
57
58    private final @Scope int mScope;
59
60    /**
61     * Creates a new provider with the given scope.
62     *
63     * @param scope Scope can't be changed at runtime.
64     */
65    protected ItemKeyProvider(@Scope int scope) {
66        checkArgument(scope == SCOPE_MAPPED || scope == SCOPE_CACHED);
67
68        mScope = scope;
69    }
70
71    final boolean hasAccess(@Scope int scope) {
72        return scope == mScope;
73    }
74
75    /**
76     * @return The selection key at the given adapter position, or null.
77     */
78    public abstract @Nullable K getKey(int position);
79
80    /**
81     * @return the position corresponding to the selection key, or RecyclerView.NO_POSITION.
82     */
83    public abstract int getPosition(@NonNull K key);
84}
85