网上都说LruCache需要重写sizeof方法,但是当我重写该方法后,发现不能缓存图片了!。。。。
代码如下:
public class MainActivity extends Activity
{
private static final String TAG = "MainActivity";
private LruCache<String,Bitmap> mMemoryCache = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
int cacheSize = maxMemory/8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize)
{
@Override
protected int sizeOf(String key, Bitmap value)
{
return value.getRowBytes()*value.getHeight();
}
};
mMemoryCache.put("aaa",BitmapFactory.decodeResource(getResources(),R.drawable.test1));
mMemoryCache.put("bbb",BitmapFactory.decodeResource(getResources(),R.drawable.test2));
mMemoryCache.put("ccc",BitmapFactory.decodeResource(getResources(),R.drawable.test3));
Log.i(TAG,"size="+mMemoryCache.size());
Bitmap bitmap = mMemoryCache.get("aaa");
if(bitmap == null)
{
Log.i(TAG,"null");
}
}
}
------解决方案--------------------
看一下Android的官方文档 http://developer.android.com/reference/android/util/LruCache.html
参考一下这个代码 :
int cacheSize = 4 * 1024 * 1024; // 4MiB
LruCache bitmapCache = new LruCache(cacheSize) {
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}}
------解决方案--------------------
http://blog.csdn.net/singwhatiwanna/article/details/17566439
------解决方案--------------------
API才是硬道理