当前位置: 代码迷 >> Android >> 【android】关于LruCache的有关问题
  详细解决方案

【android】关于LruCache的有关问题

热度:59   发布时间:2016-04-28 05:52:01.0
【android】关于LruCache的问题
网上都说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才是硬道理
  相关解决方案