我正在尝试使用Picasso库将外部图片加载到ListView
的行中。我有一个自定义的ArrayAdapter
,如下所示:
public class RevisedBusinessesAdapter extends ArrayAdapter<HashMap<String, String>> {
Context context;
int layoutResourceId;
ArrayList<HashMap<String, String>> data = null;
public RevisedBusinessesAdapter(Context context, int layoutResourceId, ArrayList<HashMap<String, String>> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RevisedBusinessHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RevisedBusinessHolder();
holder.ivLogo = (ImageView) row.findViewById(R.id.ivBusinessLogo);
row.setTag(holder);
} else {
holder = (RevisedBusinessHolder) row.getTag();
}
HashMap<String, String> business = data.get(position);
String strLogoURL = business.get("logoURL");
if (null != strLogoURL && !"".equals(strLogoURL)) {
Picasso.with(this.context).load(strLogoURL).into(holder.ivLogo);
}
return row;
}
static class RevisedBusinessHolder {
ImageView ivLogo;
}
}
当提供了logoURL作为远程图片的URL时,将显示该图片;如果未提供,则会使用本地src设置的ivBusinessLogo代替。当我快速滚动时,Picasso会将图像加载到错误的ImageView中,导致列表中出现多个重复的图像。
对于this问题的答案建议添加以下内容:
Picasso.with(context).cancelRequest(holder.ivLogo);
在现有的Picasso调用之前,但这并没有任何区别。如果我删除row == null
检查并始终创建新视图,则似乎可以正常工作。然而,在完整版本中,还有四个文本视图和五个其他图像(从本地资源加载的小图标,而不是通过Picasso)需要在每个getView
中更新。
是否有一种方法可以使用Android文档推荐的View Holder模式使其正常工作?
else holder.ivLogo.setImageBitmap(null);
。或者使用一个占位符位图。 - greenapps