我可以在显示之前使用 Picasso 下载图像吗?我想先缓存图像。
示例场景:用户单击按钮,看到进度条,当图像加载完成后,用户看到屏幕上的图像。
我尝试使用“get”方法加载图像,但没有缓存图像。
Thread thread = new Thread()
{
@Override
public void run() {
try {
Picasso picasso = PicassoOwnCache.with(getApplicationContext());
RequestCreator picassoRequest;
for (String imgUrl : imagesUrls) {
picassoRequest = picasso.load(imgUrl);
picassoRequest.get();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
这是我的毕加索单身课程
public class PicassoOwnCache {
static Picasso singleton = null;
static Cache cache = null;
public static Picasso with(int cacheSize, Context context) {
if (singleton == null) {
int maxSize = calculateMemoryCacheSize(context);
cache = new LruCache(cacheSize <= maxSize ? cacheSize : maxSize);
singleton = new Picasso.Builder(context)
.memoryCache(cache)
.build();
}
return singleton;
}
public static Picasso with(Context context) {
if (singleton == null) {
cache = new LruCache(calculateMemoryCacheSize(context));
singleton = new Picasso.Builder(context)
.memoryCache(cache)
.build();
}
return singleton;
}
static int calculateMemoryCacheSize(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
int memoryClass = am.getMemoryClass();
if (largeHeap && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);
}
return 1024 * 1024 * memoryClass / 10;//7;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class ActivityManagerHoneycomb {
static int getLargeMemoryClass(ActivityManager activityManager) {
return activityManager.getLargeMemoryClass();
}
}
}
接下来向用户显示(缓存)图像。
Picasso picasso = PicassoOwnCache.with(getApplicationContext());
picasso.setDebugging(true) ;
RequestCreator picassoRequest;
picassoRequest = picasso.load(imgUrl);
picassoRequest
.placeholder(R.drawable.loading_logo)
.error(R.drawable.no_internet)
.fit() // I tries also without fit()
.into(holder.getImageView());
不幸的是,这不起作用。感谢您的建议!