ViewCache.java revision 944779887775bd950cf1abf348d2df461593f6ab
1/* 2 * Copyright (C) 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 */ 16package com.android.tv.util; 17 18import android.content.Context; 19import android.util.SparseArray; 20import android.view.LayoutInflater; 21import android.view.View; 22import android.view.ViewGroup; 23import java.util.ArrayList; 24 25/** A cache for the views. */ 26public class ViewCache { 27 private static final SparseArray<ArrayList<View>> mViews = new SparseArray(); 28 29 private static ViewCache sViewCache; 30 31 private ViewCache() {} 32 33 /** Returns an instance of the view cache. */ 34 public static ViewCache getInstance() { 35 if (sViewCache == null) { 36 sViewCache = new ViewCache(); 37 } 38 return sViewCache; 39 } 40 41 /** Returns if the view cache is empty. */ 42 public boolean isEmpty() { 43 return mViews.size() == 0; 44 } 45 46 /** Stores a view into this view cache. */ 47 public void putView(int resId, View view) { 48 ArrayList<View> views = mViews.get(resId); 49 if (views == null) { 50 views = new ArrayList(); 51 mViews.put(resId, views); 52 } 53 views.add(view); 54 } 55 56 /** Stores multi specific views into the view cache. */ 57 public void putView(Context context, int resId, ViewGroup fakeParent, int num) { 58 LayoutInflater inflater = 59 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 60 ArrayList<View> views = mViews.get(resId); 61 if (views == null) { 62 views = new ArrayList<>(); 63 mViews.put(resId, views); 64 } 65 for (int i = 0; i < num; i++) { 66 View view = inflater.inflate(resId, fakeParent, false); 67 views.add(view); 68 } 69 } 70 71 /** Returns the view for specific resource id. */ 72 public View getView(int resId) { 73 ArrayList<View> views = mViews.get(resId); 74 if (views != null && !views.isEmpty()) { 75 View view = views.remove(views.size() - 1); 76 if (views.isEmpty()) { 77 mViews.remove(resId); 78 } 79 return view; 80 } else { 81 return null; 82 } 83 } 84 85 /** Returns the view if exists, or create a new view for the specific resource id. */ 86 public View getOrCreateView(LayoutInflater inflater, int resId, ViewGroup container) { 87 View view = getView(resId); 88 if (view == null) { 89 view = inflater.inflate(resId, container, false); 90 } 91 return view; 92 } 93 94 /** Clears the view cache. */ 95 public void clear() { 96 mViews.clear(); 97 } 98} 99