[go: nahoru, domu]

PreferenceViewHolder.java revision 6904f67c96a28a0e5966b4fb6d37a0ad5f136858
1/*
2 * Copyright (C) 2015 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 android.support.v7.preference;
18
19import android.support.annotation.IdRes;
20import android.support.v7.widget.RecyclerView;
21import android.util.SparseArray;
22import android.view.View;
23
24/**
25 * A {@link android.support.v7.widget.RecyclerView.ViewHolder} class which caches views associated
26 * with the default {@link Preference} layouts. Cached views can be retrieved by calling
27 * {@link #findViewById(int)}.
28 */
29public class PreferenceViewHolder extends RecyclerView.ViewHolder {
30    private final SparseArray<View> mCachedViews = new SparseArray<>(4);
31
32    /* package */ PreferenceViewHolder(View itemView) {
33        super(itemView);
34
35        // Pre-cache the views that we know in advance we'll want to find
36        mCachedViews.put(android.R.id.title, itemView.findViewById(android.R.id.title));
37        mCachedViews.put(android.R.id.summary, itemView.findViewById(android.R.id.summary));
38        mCachedViews.put(android.R.id.icon, itemView.findViewById(android.R.id.icon));
39        mCachedViews.put(R.id.icon_frame, itemView.findViewById(R.id.icon_frame));
40    }
41
42    /**
43     * Returns a cached reference to a subview managed by this object. If the view reference is not
44     * yet cached, it falls back to calling {@link View#findViewById(int)} and caches the result.
45     *
46     * @param id Resource ID of the view to find
47     * @return The view, or null if no view with the requested ID is found.
48     */
49    public View findViewById(@IdRes int id) {
50        final View cachedView = mCachedViews.get(id);
51        if (cachedView != null) {
52            return cachedView;
53        } else {
54            final View v = itemView.findViewById(id);
55            if (v != null) {
56                mCachedViews.put(id, v);
57            }
58            return v;
59        }
60    }
61}
62