最近我尝试使用Picasso库在Android中加载图片。据我所知,标准加载可能如下所示:
Picasso.with(mContext)
.load(source)
.placeholder(drawable_placeholder)
.resize(width, height)
.centerInside()
.into(imageView)
但是,要自定义加载某些参数(例如:占位符或noPlaceholder的布尔值usePlaceholder),我只能使用:
if (usePlaceholder) {
Picasso.with(mContext)
.load(source)
.placeholder(drawable_placeholder)
.resize(width, height)
.centerInside()
.into(imageView)
} else {
Picasso.with(mContext)
.load(source)
.resize(width, height)
.centerInside()
.into(imageView)
}
如上所示,if / else中的代码几乎相同。有没有更好的方法来以编程方式添加/删除一些requestCreators?感谢。
答案 0 :(得分:1)
您可以这样做:
RequestCreator requestCreator = Picasso.with(mContext)
.load(source)
.resize(width, height)
.centerInside();
if (usePlaceholder) {
requestCreator = requestCreator.placeholder(drawable_placeholder);
}
requestCreator.into(imageView);
答案 1 :(得分:1)
以下是您最多可以做的事情:
RequestCreator rc = Picasso.with(mContext)
.load(source)
.resize(width, height)
.centerInside();
if(usePlaceholder)
rc = rc.placeholder(R.drawable.placeholder);
rc.into(imageView);
答案 2 :(得分:0)
例如,您可以编写一个静态方法来返回名为RequestCreator
的类中的Picasso PicassoCreator
,例如
class PicassoCreator {
public static RequestCreator create(Context context, boolean isPlaceholder, String source) {
RequestCreator creator = Picasso.with(context)
.load(source);
if (isPlaceholder) {
creator.placeholder(R.drawable.placeholder);
}
return creator;
}
}
并在返回创建者之前添加其他creator.centerInside()
或creator.fit()
或creator.resize(width,height)
,并将source
参数更改为您拥有的任何内容(我的示例可能是一个URL)。然后在您的代码中使用它,如
PicassoCreator.create(getContext(),true, "https://example.com/image.jpeg")
.into(view);