【发布时间】:2013-04-16 14:39:10
【问题描述】:
我有带有 EventAdapter 的 ListView。
public class EventAdapter extends BaseAdapter {
...
public View getView(int position, View view, ViewGroup parent) {
...
cache.imgIcon.setImageDrawable(ImgCache.setImg(url, progressBar));
...
}
ImgCache 其用于缓存图像的类。
public class ImgCache {
public static HashMap<String, Drawable> imgCache;
// get img from cache if exist, or download and put in cache
public static Drawable setImg(final String link, final ProgressBar progressBar) {
final Drawable[] image = {null};
if (imgCache.containsKey(link)) {
image[0] = imgCache.get(link);
progressBar.setVisibility(View.INVISIBLE);
} else {
new AsyncTask<Void, Void, Drawable>() {
@Override
protected Drawable doInBackground(Void... params) {
URL url = null;
try {
url = new URL(link);
URLConnection connection = url.openConnection();
image[0] = Drawable.createFromStream(connection.getInputStream(), "src");
} catch (Exception e) {
e.printStackTrace();
}
imgCache.put(link, image[0]);
return image[0];
}
@Override
protected void onPostExecute(Drawable result) {
progressBar.setVisibility(View.INVISIBLE);
}
}.execute();
}
return image[0];
}
}
问题是什么?
在我用ListView 打开我的Activity 后,所有图像都开始加载。但是加载完成后它们不会显示。它看起来像:
然后我尝试向下滚动 2 个项目,然后返回到之前的位置。完成此操作后,我可以看到 2 个带有图像的上部项目。当我滚动到它们时,也可以看到所有向下的图像。
【问题讨论】:
-
只是一个警告:
HashMap<String, Drawable>取决于您拥有的可绘制对象数量以及用户使用的设备,您的应用会出现 OutOfMemory 错误。 -
我可以得到这个 HashMap 的大小吗?缓存的大小必须是多少?
-
用于图像缓存(我通常使用Bitmap,但Drawable也一样)我建议你使用LruCache(developer.android.com/reference/android/support/v4/util/…)
标签: android listview caching android-asynctask android-imageview