class ImageManager {
private WeakHashMap<Integer, WeakReference<Bitmap>> mBitmaps;
private WeakHashMap<Integer, WeakReference<Drawable》> mDrawables;
private boolean mActive = true;
public ImageManager() {
mBitmaps = new WeakHashMap<Integer, WeakReference<Bitmap>>();
mDrawables = new WeakHashMap<Integer, WeakReference<Drawable>>();
}
public Bitmap getBitmap(int resource) {
if (mActive) {
if (!mBitmaps.containsKey(resource)) {
mBitmaps.put(resource,
new WeakReference<Bitmap>(BitmapFactory.decodeResource(MainActivity.getContext().getResources(), resource)));
}
return ((WeakReference<Bitmap>)mBitmaps.get(resource)).get();
}
return null;
}
public Drawable getDrawable(int resource) {
if (mActive) {
if (!mDrawables.containsKey(resource)) {
mDrawables.put(resource, new WeakReference<Drawable>(getApplication().getResources().getDrawable(resource)));
}
return ((WeakReference<Drawable>)mDrawables.get(resource)).get();
}
return null;
}
public void recycleBitmaps() {
Iterator itr = mBitmaps.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry)itr.next();
((WeakReference<Bitmap>) e.getValue()).get().recycle();
}
mBitmaps.clear();
}
public ImageManager setActive(boolean b) {
mActive = b;
return this;
}
public boolean isActive() {
return mActive;
}
}
参考链接:1/2