• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 package com.android.launcher3.util;
17 
18 import android.content.Context;
19 import android.util.SparseArray;
20 import android.view.LayoutInflater;
21 import android.view.View;
22 import android.view.ViewGroup;
23 
24 /**
25  * Utility class to cache views at an activity level
26  */
27 public class ViewCache {
28 
29     protected final SparseArray<CacheEntry> mCache = new SparseArray();
30 
setCacheSize(int layoutId, int size)31     public void setCacheSize(int layoutId, int size) {
32         mCache.put(layoutId, new CacheEntry(size));
33     }
34 
getView(int layoutId, Context context, ViewGroup parent)35     public <T extends View> T getView(int layoutId, Context context, ViewGroup parent) {
36         CacheEntry entry = mCache.get(layoutId);
37         if (entry == null) {
38             entry = new CacheEntry(1);
39             mCache.put(layoutId, entry);
40         }
41 
42         if (entry.mCurrentSize > 0) {
43             entry.mCurrentSize --;
44             T result = (T) entry.mViews[entry.mCurrentSize];
45             entry.mViews[entry.mCurrentSize] = null;
46             return result;
47         }
48 
49         return (T) LayoutInflater.from(context).inflate(layoutId, parent, false);
50     }
51 
recycleView(int layoutId, View view)52     public void recycleView(int layoutId, View view) {
53         CacheEntry entry = mCache.get(layoutId);
54         if (entry != null && entry.mCurrentSize < entry.mMaxSize) {
55             entry.mViews[entry.mCurrentSize] = view;
56             entry.mCurrentSize++;
57         }
58     }
59 
60     private static class CacheEntry {
61 
62         final int mMaxSize;
63         final View[] mViews;
64 
65         int mCurrentSize;
66 
CacheEntry(int maxSize)67         public CacheEntry(int maxSize) {
68             mMaxSize = maxSize;
69             mViews = new View[maxSize];
70             mCurrentSize = 0;
71         }
72     }
73 }
74