ViewPool.java revision 303e1ff1fec8b240b587bb18b981247a99833aa8
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    Context mContext;
28    ViewPoolConsumer<V, T> mViewCreator;
29    LinkedList<V> mPool = new LinkedList<V>();
30
31    /** Initializes the pool with a fixed predetermined pool size */
32    public ViewPool(Context context, ViewPoolConsumer<V, T> viewCreator) {
33        mContext = context;
34        mViewCreator = viewCreator;
35    }
36
37    /** Returns a view into the pool */
38    void returnViewToPool(V v) {
39        mViewCreator.prepareViewToEnterPool(v);
40        mPool.push(v);
41    }
42
43    /** Gets a view from the pool and prepares it */
44    V pickUpViewFromPool(T preferredData, T prepareData) {
45        V v = null;
46        boolean isNewView = false;
47        if (mPool.isEmpty()) {
48            v = mViewCreator.createView(mContext);
49            isNewView = true;
50        } else {
51            // Try and find a preferred view
52            Iterator<V> iter = mPool.iterator();
53            while (iter.hasNext()) {
54                V vpv = iter.next();
55                if (mViewCreator.hasPreferredData(vpv, preferredData)) {
56                    v = vpv;
57                    iter.remove();
58                    break;
59                }
60            }
61            // Otherwise, just grab the first view
62            if (v == null) {
63                v = mPool.pop();
64            }
65        }
66        mViewCreator.prepareViewToLeavePool(v, prepareData, isNewView);
67        return v;
68    }
69}
70