gpt4 book ai didi

Android Glide : How to download and cache bitmaps?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:56:31 26 4
gpt4 key购买 nike

我正在使用 Glide 在 Android 上下载和缓存图像。一切正常,除了我不想将位图直接加载到 ImageView 中,我不想有淡入淡出动画,也不想图像占位符。

我只想创建一个全局方法来帮助我在整个应用程序中下载图像。

public class MyApp extends Application {

public static void downloadImage(String url, final OnImageLoadedCallback callback) {

// And how to implement the listener ?

RequestListener<String, Bitmap> requestListener = new RequestListener<String, Bitmap() {
@Override
public boolean onException(Exception exc, String string, Target<Bitmap> target, boolean isFirstResource) {

callback.onDone(null);

return false;
}

@Override
public boolean onResourceReady(Bitmap bitmap, String string, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {

callback.onDone(bitmap);

return false;
}
};

Glide.with(context)
.load(url)
.asBitmap()
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.listener(requestListener);
}

}

问题是我不知道如何实现监听器。 RequestListener 根本没有被调用。

最佳答案

在您调用 into 之前,Glide 中的加载不会开始. RequestListener 接口(interface)观察请求,但通常不用于处理结果。不要使用 RequestListener,考虑让你的回调实现 Target接口(interface)并使用 into 传递它.

或者你可以扩展 SimpleTarget并以与您尝试使用 RequestListener 相同的方式将其传递给每个请求:

Target target = Glide.with(context)
...
.into(new SimpleTarget<Bitmap>(width, height) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
callback.onDone(resource);
}

@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
callback.onDone(null);
}
});

// At some point later, if you want to cancel the load:
Glide.clear(target);

您需要提供宽度和高度,以便 Glide 可以适本地缩减采样和转换图像。如果您在 View 中显示这些位图,您也可能会遇到取消问题,在这种情况下,我强烈建议您将 View 提供给您的加载 API,并将 View 传递给 into。它将为您处理大小调整和取消。

关于Android Glide : How to download and cache bitmaps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27640307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com