0

我正在制作一个 android 应用程序,其中有带有缩略图的新闻文章。这些缩略图从网络加载并存储在 LruCache 中,其中 URL 作为键,位图作为值。

private LruCache<String, Bitmap> tCache;

在适配器的 getView() 方法中,我调用 getThumbnail() 检查缓存(必要时从网络加载)然后显示缩略图。

public void populateList(){
    ...
    new Thread(new Runnable() {
        @Override
        public void run() {
            getThumbnail(story, thumbnail);
        }
    }).start();
}

private Bitmap getThumbnail(Story story, ImageView imageView) {
    String url = story.getThumbnail();

    Bitmap bitmap;
    synchronized (tCache) {
        bitmap = tCache.get(url);

        if (bitmap == null) {

            bitmap = new ImageLoadingUtils(this, imageView).execute(url,
                    Boolean.TRUE).get();
            tCache.put(url, bitmap);

        }
    }
    return bitmap;

}

ImageLoadingUtils 从网络加载,完成后将生成的位图放入 ImageView。

@Override
protected void onPostExecute(Bitmap result) {
    if (imageView != null) {
        imageView.setImageBitmap(result);
        adapter.notifyDataSetChanged();
    }
}

问题是当我向下滚动时缩略图会在同一个 ListView 中重复。

________
|图像1|
|图像2|
|图像3| 屏幕
|图像4|
--------
|图像1|
|图像2| 屏幕外
________

当我向下滚动然后向上滚动时,这些文章不再具有正确的缩略图。它非常混乱。

任何人都可以发现问题吗?十分感谢。

4

2 回答 2

2

问题是因为视图在列表视图中被重用。这是一个关于如何在列表视图中异步缓存和加载缩略图的好例子。

延迟加载 ListView Android

于 2012-12-30T15:49:47.873 回答
0

如果您的适配器的 getView 方法包含如下行:

@Override
public View getView(int position, View convertView, ViewGroup parent) {     
   if(convertView == null){
       LayoutInflater inflater = (LayoutInflater) context.getSystemService(...);
       convertView = inflater.inflate(...);
   }
}

删除这个“if”条件,只保留内部代码,例如:

@Override
public View getView(int position, View convertView, ViewGroup parent) {    
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(...);
    convertView = inflater.inflate(...);
}
于 2016-02-22T18:11:56.757 回答