代码之家  ›  专栏  ›  技术社区  ›  Ragunath Jawahar cephus

软引用中Drawable的延迟加载失败

  •  2
  • Ragunath Jawahar cephus  · 技术社区  · 14 年前

    public class ImageCache {
        HashMap<String, SoftReference<Drawable>> myCache;
        ....
        ....
        public void putImage(String key, Drawable d) {
            myCache.put(key, new SoftReference<Drawable>(d));
        }
    
        public Drawable getImage(String key) {
            Drawable d;
            SoftReference<Drawable> ref = myCache.get(key);
    
            if(ref != null) {
                //Get drawable from reference
                //Assign drawable to d
            } else {
                //Retrieve image from source and assign to d
                //Put it into the HashMap once again
            }
            return d;
        }
    }
    

    我有一个自定义适配器,通过从缓存中检索drawable来设置ImageView的图标。

    public View getView(int position, View convertView, ViewGroup parent) {
        String key = myData.get(position);
        .....
        ImageView iv = (ImageView) findViewById(R.id.my_image);
        iv.setImageDrawable(myCache.getImage(key));
        .....
    }
    

    但是当我运行程序时,ListView中的大部分图像在一段时间后消失了,其中一些甚至一开始就不在了。我用硬引用替换了HashMap。比如,

    HashMap<String, Drawable> myCache
    

    这段代码是有效的。我想优化我的代码。任何建议。

    2 回复  |  直到 14 年前
        1
  •  4
  •   hackbod    14 年前

        if(ref != null) {
            //Get drawable from reference
            //Assign drawable to d
        } else {
            //Retrieve image from source and assign to d
            //Put it into the HashMap once again
        }
    

    如果软引用已被释放,您将在第一个条件下结束,而不是检测到它,也不会重新加载图像。你需要做更多这样的事情:

        Drawable d = ref != null ? ref.get() : null;
        if (d == null) {
            //Retrieve image from source and assign to d
            //Put it into the HashMap once again
        }
        //Get drawable from reference
        //Assign drawable to d
    

    该平台广泛使用弱引用来缓存从资源和其他东西加载的drawable,因此,如果您从资源获取东西,您可以让它为您处理。

        2
  •  2
  •   Fedor    14 年前

    Android中的SoftReference存在一个已知问题。他们可能会被提前释放,你不能依赖他们。
    http://groups.google.com/group/android-developers/browse_thread/thread/ebabb0dadf38acc1
    为了解决这个问题,我必须编写自己的软引用实现。