1 /* 2 * Copyright (C) 2014 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 17 package com.android.systemui.recents.views; 18 19 import android.content.Context; 20 21 import java.util.Iterator; 22 import java.util.LinkedList; 23 import java.util.List; 24 25 26 /* A view pool to manage more views than we can visibly handle */ 27 public class ViewPool<V, T> { 28 29 /* An interface to the consumer of a view pool */ 30 public interface ViewPoolConsumer<V, T> { createView(Context context)31 public V createView(Context context); onReturnViewToPool(V v)32 public void onReturnViewToPool(V v); onPickUpViewFromPool(V v, T prepareData, boolean isNewView)33 public void onPickUpViewFromPool(V v, T prepareData, boolean isNewView); hasPreferredData(V v, T preferredData)34 public boolean hasPreferredData(V v, T preferredData); 35 } 36 37 Context mContext; 38 ViewPoolConsumer<V, T> mViewCreator; 39 LinkedList<V> mPool = new LinkedList<V>(); 40 41 /** Initializes the pool with a fixed predetermined pool size */ ViewPool(Context context, ViewPoolConsumer<V, T> viewCreator)42 public ViewPool(Context context, ViewPoolConsumer<V, T> viewCreator) { 43 mContext = context; 44 mViewCreator = viewCreator; 45 } 46 47 /** Returns a view into the pool */ returnViewToPool(V v)48 void returnViewToPool(V v) { 49 mViewCreator.onReturnViewToPool(v); 50 mPool.push(v); 51 } 52 53 /** Gets a view from the pool and prepares it */ pickUpViewFromPool(T preferredData, T prepareData)54 V pickUpViewFromPool(T preferredData, T prepareData) { 55 V v = null; 56 boolean isNewView = false; 57 if (mPool.isEmpty()) { 58 v = mViewCreator.createView(mContext); 59 isNewView = true; 60 } else { 61 // Try and find a preferred view 62 Iterator<V> iter = mPool.iterator(); 63 while (iter.hasNext()) { 64 V vpv = iter.next(); 65 if (mViewCreator.hasPreferredData(vpv, preferredData)) { 66 v = vpv; 67 iter.remove(); 68 break; 69 } 70 } 71 // Otherwise, just grab the first view 72 if (v == null) { 73 v = mPool.pop(); 74 } 75 } 76 mViewCreator.onPickUpViewFromPool(v, prepareData, isNewView); 77 return v; 78 } 79 80 /** 81 * Returns the list of views in the pool. 82 */ getViews()83 List<V> getViews() { 84 return mPool; 85 } 86 } 87