获取系统分配的内存大小
private int mTotalSize = (int) Runtime.getRuntime().totalMemory();
声明LruCache
private LruCache<String,Bitmap> mLruCache ;
/*实例化LruCache*/
mLruCache = new LruCache<String,Bitmap>(mTotalSize/5){
/*当缓存大于我们设定的最大值时,会调用这个方法,我们可以用来做内存释放操作*/
@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
super.entryRemoved(evicted, key, oldValue, newValue);
if (evicted && oldValue != null){
oldValue.recycle();
}
}
/*创建 bitmap*/
@Override
protected Bitmap create(String key) {
final int resId = mViewPager.getResources().getIdentifier(key,"drawable",
mViewPager.getContext().getPackageName()) ;
return BitmapFactory.decodeResource(mViewPager.getResources(),resId) ;
}
/*获取每个 value 的大小*/
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
} ;
}
获取bitmap
Bitmap bitmap = mLruCache.get(mData.get(position));