You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Glide实现单图复用至多个ImageView的内存优化方案

如何用Glide只加载一次图片并显示在多个ImageView中

嘿,这个问题我太懂了——重复加载同一张图确实会白白占用内存,Glide其实自带了缓存机制,而且还有更直接的方法实现单次加载、多View复用的需求,我给你整理两个最靠谱的方案:

方案一:利用Glide的缓存机制(预加载+复用缓存)

Glide默认会对加载的资源做内存和磁盘缓存,我们可以先把图片预加载到缓存里,之后再加载到两个ImageView时,就会直接读取缓存,不会重复请求资源:

// 第一步:预加载图片到Glide的缓存中
Glide.with(this)
     .load(R.drawable.header_image)
     .preload();

// 第二步:分别加载到两个ImageView,此时会直接复用缓存资源
ImageView imageView1 = findViewById(R.id.header_image1);
ImageView imageView2 = findViewById(R.id.header_image2);

Glide.with(this)
     .load(R.drawable.header_image)
     .into(imageView1);
Glide.with(this)
     .load(R.drawable.header_image)
     .into(imageView2);

这个方法的好处是不用手动管理资源,完全依托Glide的缓存体系,代码也简洁。

方案二:手动获取资源后复用(更直接的方式)

如果想更主动地控制资源,我们可以用CustomTarget拿到加载完成的Drawable,然后手动设置给两个ImageView,这样整个过程只加载一次:

ImageView imageView1 = findViewById(R.id.header_image1);
ImageView imageView2 = findViewById(R.id.header_image2);

Glide.with(this)
     .load(R.drawable.header_image)
     .into(new CustomTarget<Drawable>() {
         @Override
         public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
             // 将同一个Drawable设置给两个ImageView
             imageView1.setImageDrawable(resource);
             imageView2.setImageDrawable(resource);
         }

         @Override
         public void onLoadCleared(@Nullable Drawable placeholder) {
             // 可选:当资源被清理时的回调,比如做一些内存释放操作
         }
     });

这种方式更直观,完全避免了重复加载的可能,适合对内存控制要求较高的场景。

另外补充一句:其实Glide默认的内存缓存策略(MemoryCacheStrategy.AUTOMATIC)已经会自动缓存最近加载的资源,所以如果你只是连续两次调用into()加载同一张图,大概率已经不会重复加载了,但上面的两种方法能更稳妥地确保这一点,消除你的顾虑~

内容的提问来源于stack exchange,提问作者Ashuthosh Patoa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:24:41