【发布时间】: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