Picasso library允许用户轻松加载图像:
Picasso.with(context).load(url).into(imageview);
API还允许指定错误图像。但是,如果我希望图书馆在放弃并显示错误图像之前首先尝试三到四个不同的URL,我该怎么办?理想情况下,这些图像将按顺序进行尝试,如果之前没有加载,则会回到下一个图像。
答案 0 :(得分:4)
本地没有这种功能的API。但是使用一些聪明的编码Picasso.Target,您可以轻松实现此类功能。
我将在这里添加一个快速的黑客未经测试的代码,该代码可以让您对要查找的内容有所了解。你必须测试,也许要微调,但那应该还不错。
private static final List<MultiFallBackTarget> TARGETS = new ArrayList<MultiFallBackTarget>();
public static class MultiFallBackTarget implements Picasso.Target {
private WeakReference<ImageView> weakImage;
private List<String> fallbacks;
public MultiFallBackTarget(ImageView image){
weakImage = new WeakReference<>(image);
fallbacks = new ArrayList<String>();
TARGETS.add(this);
}
public void addFallback(String fallbackUrl){
fallbacks.add(fallbackUrl);
}
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from){
removeSelf();
ImageView image = weakImage.get();
if(image == null) return;
image.setImageBitmap(bitmap);
}
public void onBitmapFailed(Drawable errorDrawable){
ImageView image = weakImage.get();
if(image == null) {
removeSelf();
return;
}
if(fallbacks.size() > 0){
String nextUrl = fallbacks.remove(0);
// here you call picasso again
Picasso.with(image.getContext()).load(nextUrl).into(this);
} else {
removeSelf();
}
}
public void onPrepareLoad(Drawable placeHolderDrawable){}
private void removeSelf(){
TARGETS.remove(this);
}
}
请记住,毕加索没有强烈引用你放在into(object)
内的目标。这意味着,毕加索内部使用WeakReference。
这意味着您需要TARGETS
中的自我引用来继续引用您创建的所有MultiFallBackTarget
,并允许他们在完成工作时自行删除。