缓存需要使用到SoftReference
step 1:定义ImageCahce
public class ImageCache{
private final HashMap<String, SoftReference<Bitmap>> mSoftCache;
public ImageCache(Context context) {
mSoftCache = new HashMap<String, SoftReference<Bitmap>>();
}
public Bitmap get(String url) {
final SoftReference<Bitmap> ref = mSoftCache.get(url);
if (ref == null) {
return null;
}
Bitmap bitmap = ref.get();
if (bitmap == null) {
mSoftCache.remove(url);
}
return bitmap;
}
public void put(String url, Bitmap bitmap) {
mSoftCache.put(url, new SoftReference<Bitmap>(bitmap));
}
private void flush() {
mSoftCache.clear();
}
}
step 2:application 中定义ImageCache成员变量
private ImageCache mImageCache;
public ImageCache getImageCache() {
if (mImageCache == null) {
mImageCache = new ImageCache(this);
}
return mImageCache;
}