Example using Androids lrucache

前端 未结 5 2024
予麋鹿
予麋鹿 2020-12-02 09:02

I need help understanding androids LruCache. I want to use to load images into my gridview in order make the loading/scrolling better. Can someone post an example code using

5条回答
  •  遥遥无期
    2020-12-02 09:16

    Utility Class to save and retrieve Bitmap from own Cache.

    package com.roomco.android.utils;
    
    import android.graphics.Bitmap;
    import android.support.v4.util.LruCache;
    
    
    public class MyCache {
    
          private static MyCache instance;
          private LruCache lru;
    
          private MyCache() {
    
             lru = new LruCache(1024);
    
           }
    
        public static MyCache getInstance() {
    
            if (instance == null) {
            instance = new MyCache();
           }
           return instance;
    
        }
    
       public LruCache getLru() {
           return lru;
       }
    
      public void saveBitmapToCahche(String key, Bitmap bitmap){
    
          MyCache.getInstance().getLru().put(key, bitmap);
      }
    
      public Bitmap retrieveBitmapFromCache(String key){
    
          Bitmap bitmap = (Bitmap)MyCache.getInstance().getLru().get(key);
          return bitmap;
      }
    
    }
    

    Usage:

    //Save bitmap in cache
    MyCache.getInstance().saveBitmapToCahche("your_key",bitmap);
    // Get bitmap from cache
    MyCache.getInstance().retrieveBitmapFromCache("your_key");
    

提交回复
热议问题