private class CustomAdapter extends CursorAdapter {
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view != null) {
String url = cursor.getString(CONTENT_URL_COLUMN);
ViewHolder viewHolder = (ViewHolder) view.getTag();
final ImageView imageView = viewHolder.mImageViewIcon;
final TextView textView = viewHolder.mTextViewName;
Picasso.with(context).load(url).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap arg0, LoadedFrom arg1) {
imageView.setImageBitmap(arg0);
imageView.setVisibility(View.VISIBLE);
textView.setVisibility(View.GONE);
}
@Override
public void onBitmapFailed(Drawable arg0) {
imageView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
}
});
}
}
}
}
如果已下载图像列表,则快速滚动列表, 调用 onBitmapLoaded()方法并从内存缓存中加载图像。但有时会调用 onBitmapFailed()。为什么?
答案 0 :(得分:7)
您的Target
正在被垃圾收集,因为没有任何内容可以引用它。 Picasso在持有WeakReference
或ImageView
s时使用Target
。
但是,您根本不需要使用Target
。只需使用.into
的回调并直接传递ImageView
。
Picasso.with(context).load(url).into(imageView, new Callback() {
@Override public void onSuccess() {
imageView.setVisibility(VISIBLE);
textView.setVisibility(GONE);
}
@Override public void onError() {
imageView.setVisibility(GONE);
textView.setVisibility(VISIBLE);
}
});