我正在使用 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/