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