Search code examples
androidimagememory-managementandroid-resources

RecyclerView image reuse


I have an app that reuses images in a recyclerview. I'd like to know the best way to save resources using the same images repeatedly. My knowledge of memory use is none at best.

I have an image that gets scaled depending on its use in the app, but when in the list what is the best way to display the same image. Is the image memory getting reused for either of these or is each image taking of a chunk of memory separately. Is there a better way?

   pholder.nodeImage.setImageBitmap(Tools.decodeSampledBitmapFromResource(context.getResources(),R.drawable.folder,50,50));
    or
   pholder.nodeImage.setImageResource(R.drawable.folder);

Solution

  • Put your images in a cache, you can use the LruCache class Images are cached during the app lifecycle and discarded when the app exists. You can adjust the cache sized based on the expected number of images to cache, their size, and the device the app is running on.

    int cacheSize = 4 * 1024 * 1024; // 4MiB
    LruCache bitmapCache = new LruCache(cacheSize) {
       protected int sizeOf(String key, Bitmap value) {
           return value.getByteCount();
        }
    }
    
    
    synchronized (cache) {
     if (cache.get(key) == null) {
         cache.put(key, value);
        }
    }