Android SoftReferences中Drawable的延迟加载失败

Android SoftReferences中Drawable的延迟加载失败,android,optimization,user-interface,listview,lazy-loading,Android,Optimization,User Interface,Listview,Lazy Loading,我有一个包含100个不同图像的列表视图。我的缓存如下所示 public class ImageCache { HashMap<String, SoftReference<Drawable>> myCache; .... .... public void putImage(String key, Drawable d) { myCache.put(key, new SoftReference<Drawable>(d

我有一个包含100个不同图像的列表视图。我的缓存如下所示

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;
    }
}
但当我运行程序时,ListView中的大多数图像在一段时间后消失,其中一些甚至根本不存在。我用硬引用替换了HashMap。像

HashMap<String, Drawable> myCache
HashMap-myCache

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

Android中的SoftReference存在一个已知问题。他们可能被提前释放,你不能依赖他们。


为了解决这个问题,我必须编写自己的SoftReference实现。

这段代码看起来有问题:

    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

该平台广泛使用弱引用来缓存从资源和其他内容加载的可绘制内容,因此,如果您从资源中获取内容,您可以让它为您解决这一问题。

是否有机会共享该实现?我还发现在Android中使用SoftReference释放资源的速度太快了。
    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