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 import com.android.launcher3.R; 25 26 /** 27 * Utility class to cache views at an activity level 28 */ 29 public class ViewCache { 30 31 protected final SparseArray<CacheEntry> mCache = new SparseArray(); 32 setCacheSize(int layoutId, int size)33 public void setCacheSize(int layoutId, int size) { 34 mCache.put(layoutId, new CacheEntry(size)); 35 } 36 getView(int layoutId, Context context, ViewGroup parent)37 public <T extends View> T getView(int layoutId, Context context, ViewGroup parent) { 38 CacheEntry entry = mCache.get(layoutId); 39 if (entry == null) { 40 entry = new CacheEntry(1); 41 mCache.put(layoutId, entry); 42 } 43 44 T result; 45 if (entry.mCurrentSize > 0) { 46 entry.mCurrentSize --; 47 result = (T) entry.mViews[entry.mCurrentSize]; 48 entry.mViews[entry.mCurrentSize] = null; 49 } else { 50 result = (T) LayoutInflater.from(context).inflate(layoutId, parent, false); 51 result.setTag(R.id.cache_entry_tag_id, entry); 52 } 53 return result; 54 } 55 recycleView(int layoutId, View view)56 public void recycleView(int layoutId, View view) { 57 CacheEntry entry = mCache.get(layoutId); 58 if (entry != view.getTag(R.id.cache_entry_tag_id)) { 59 // Since this view was created, the cache has been reset. The view should not be 60 // recycled since this means the environment could also have changed, requiring new 61 // view setup. 62 return; 63 } 64 if (entry != null && entry.mCurrentSize < entry.mMaxSize) { 65 entry.mViews[entry.mCurrentSize] = view; 66 entry.mCurrentSize++; 67 } 68 } 69 70 private static class CacheEntry { 71 72 final int mMaxSize; 73 final View[] mViews; 74 75 int mCurrentSize; 76 CacheEntry(int maxSize)77 public CacheEntry(int maxSize) { 78 mMaxSize = maxSize; 79 mViews = new View[maxSize]; 80 mCurrentSize = 0; 81 } 82 } 83 } 84