【问题标题】:Lazy loading of Drawable fails in SoftReferences在 SoftReferences 中延迟加载 Drawable 失败
【发布时间】:2011-04-18 15:01:56
【问题描述】:

我有一个包含 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;
    }
}

我有一个自定义适配器,通过从缓存中检索可绘制对象来设置 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

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

【问题讨论】:

    标签: android optimization user-interface listview lazy-loading


    【解决方案1】:

    这段代码看起来坏了:

        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
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 您想分享一下这个实现吗?我还发现在 Android 中使用 SoftReference 太快地释放资源。
      猜你喜欢
      • 2014-04-03
      • 2018-02-27
      • 1970-01-01
      • 2017-07-30
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      相关资源
      最近更新 更多