android - Picasso 将图片加载到列表适配器中的错误 ImageView

标签 android listview android-listview picasso

我正在使用 picasso 将图像从服务器加载到 ListView 项,如下所示:

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View participantView;
    if(convertView == null) {
        participantView = inflater.inflate(R.layout.participant_item, parent, false);
    } else {
        participantView = convertView;
    }

    TextView textView = (TextView) participantView.findViewById(R.id.participantName);
    textView.setText(getItem(position).getName());
    ImageView imageView = (ImageView) participantView.findViewById(R.id.participantImage);
    String profilePic = getItem(position).getProfilePic();

    if(!profilePic.equals("None")) {
        Log.d("tom.debug", "creating picture for user: " + getItem(position).getName());
        Picasso.with(this.context)
            .load(urlToProfilePics + profilePic)
            .placeholder(R.drawable.sample_0)
            .resize(52, 52)
            .into(imageView);
    } else {
        //load the place holder into the image view
        Picasso.with(this.context).load(R.drawable.sample_0);
    }

    if(!getItem(position).isHere()) {
        imageView.setColorFilter(Color.DKGRAY, PorterDuff.Mode.MULTIPLY);
    }

    return participantView;
}

if 语句下的调试日志仅针对真正拥有个人资料图片的用户触发。 (没有的用户将获得 None 的值)。

但是,一些其他 ListView 项(没有个人资料图片)也会加载图片。

另一个有用的事实(我认为):当向上和向下滚动列表时,出现错误的项目会发生变化。

我不确定我在这里缺少什么。

最佳答案

确保每次您要在适配器的 getView() 上使用 Picasso 时调用 cancelRequest

// 1st: reset the imageView
Picasso.with(this.context).cancelRequest(holder.imageView); 

// 2nd start a new load for the imageView
Picasso.with(this.context).load(...).into(holder.imageView); 

原因是您从 convertView 参数重用的 View 属于可能已经被 Picasso 加载用于另一张图片的前一行。

这只有在使用 convertView 时才真正需要,如果您刚刚扩充了一个新布局,则不需要它..但是您可以随时调用以使您的代码更容易。 p>

关于android - Picasso 将图片加载到列表适配器中的错误 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25429683/

相关文章:

android:slidingDrawer 不显示 ListView 内容?

android - 尝试在运行 4.2 的设备上访问 Picasa 图像时出现安全异常

java - 安卓:Epub 文件在模拟器/安卓设备中不显示图像

java - 如何用新列表替换ListView的列表

android - 在列表中的最后一项之后显示分隔符

java - 在 Android 中将对象添加到 ArrayList 时出现 NullPointerException

java - Android 自定义适配器和 asyncTask 不更新 listView

android - 加载全宽和全高图像

c# - 具有 AutoScroll 性能的虚拟化 ListView(慢)

android - 滚动我的自定义 ListView 时复选框丢失选中值