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