我在我的Android应用中使用Glide进行图像加载,为避免崩溃,我正在使用应用程序上下文加载图像。这对应用程序的性能和内存有什么影响?
static loadImage(RequestManager glide, String url, ImageView view) {
glide.load(url).into(view);
}
或者在适配器中:
class MyAdapter extends WhichEveryOneYouUse {
private final RequestManager glide;
MyAdapter(RequestManager glide, ...) {
this.glide = glide;
...
}
void getView/onBindViewHolder(... int position) {
// ... holder magic, and get current item for position
glide.load... or even loadImage(glide, item.url, holder.image);
}
}
并从Activity / Fragment中使用它们:
loadImage(Glide.with(this), url, findViewById(R.id.image));
// or
list.setAdapter(new MyAdapter(Glide.with(this), data));
private fun RequestManager.syncWithLifecycleOwner(view: View): RequestManager {
val syncRequest = object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) = onStart()
override fun onStop(owner: LifecycleOwner) = onStop()
override fun onDestroy(owner: LifecycleOwner) {
onDestroy()
owner.lifecycle.removeObserver(this)
}
}
view.findViewTreeLifecycleOwner()?.lifecycle?.addObserver(syncRequest)
return this
然后,您可以创建一个简单的扩展函数,如下所示:
fun ImageView.loadUrl(url: String) {
Glide
.with(context.applicationContext)
.syncWithLifecycleOwner(this)
.load(url)
.into(this)
}
findViewTreeLifecycleOwner()
函数在 AndroidX 生命周期库中。它提供了 Activity 或 Fragment 中的 View 生命周期(viewLifecycleOwner
),这个特定的 ImageView 依附于其中。你需要传递来自视图内部的应用程序上下文,以确保 Glide 库不会自行调用回调函数。
Glide.with(view.getContext())
实际上等同于Glide.with(this)
,因为RequestManagerRetriever.get(Context context)
会检查上下文是否是Activity
的实例并适当地进行转换,例如get((Activity)context)
。因此,无论哪种方式,它最终都将使用相同的get(Activity)
方法。 - Lorne Laliberteload
,Coil 也会使用 Activity 的生命周期。但是,Coil 和 Glide 都会响应View.onDetach
事件,当一个 Fragment 被移动到后台时会触发该事件。此外,由于 Coil 使用了 AndroidX 生命周期组件,所以在销毁的 Activity 内部发起的任何请求都将立即被取消。 - Colin White