假设我有一个包含 4 个 ImageView 的布局。每个 ImageView 必须包含从远程 url 下载的图片。我可以像这样使用 Picasso 库轻松完成这样的任务:
Picasso.with(context)
.load(photo1Url)
.placeholder(R.drawable.image_view_placeholder)
.error(R.drawable.image_view_error_placeholder)
.centerCrop()
.tag(context)
.fit()
.into(feedListViewPhoto1);
Picasso.with(context)
.load(photo2Url)
.placeholder(R.drawable.image_view_placeholder)
.error(R.drawable.image_view_error_placeholder)
.centerCrop()
.tag(context)
.fit()
.into(feedListViewPhoto2);
Picasso.with(context)
.load(photo3Url)
.placeholder(R.drawable.image_view_placeholder)
.error(R.drawable.image_view_error_placeholder)
.fit()
.centerCrop()
.tag(context)
.fit()
.into(feedListViewPhoto3);
Picasso.with(context)
.load(photo4Url)
.placeholder(R.drawable.image_view_placeholder)
.error(R.drawable.image_view_error_placeholder)
.centerCrop()
.tag(context)
.fit()
.into(feedListViewPhoto4);
但也许有更紧凑的解决方案来实现这样的目标?例如:只写一次“Picasso with”并传递所有必需的 url 和 ImageView 对象引用?也许某种for
循环解决方案会有所帮助?
最佳答案
我强烈建议您在您的应用程序中创建一个 ImageLoader“服务”。
首先,创建一个接口(interface),其中包含下载图像并设置到 ImageView
或获取位图或相关功能所需的方法:
public interface ImageService {
public void downloadAndSetImage(Context context, String url, ImageView image);
//Other important methods to you
}
有了这个,你就可以用 Picasso 或其他下载系统来实现了。例如,这对于在不破坏您的应用程序的情况下更改或测试其他系统很有用。
之后,使用所有样板代码创建方法的实现。
public class PicassoImageImpl implements ImageService {
@Override
public void downloadAndSetImage(Context context, ImageDownloadInfo imageDownloadInfo) {
//All picasso code
}
}
然后在您的应用程序中,您只需实例化您的 ImageService(我强烈建议您使用 DependencyInyection 或至少一个中央工厂来获取实例)并简单地调用您需要的方法。
关于java - 使用 Picasso 库加载图像时如何避免样板代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32167948/