我正在使用ListView来显示与这些图像相关的一些图像和标题。我正在从互联网上获取图像。是否有一种方法可以延迟加载图像,以便在文本显示时,UI不会被阻止,图像在下载时显示?

图像总数不是固定的。


当前回答

使用滑动库。它适用于我,也适用于你的代码。它也适用于图像和gif。

ImageView imageView = (ImageView) findViewById(R.id.test_image); 
    GlideDrawableImageViewTarget imagePreview = new GlideDrawableImageViewTarget(imageView);
    Glide
            .with(this)
            .load(url)
            .listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {                       
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    return false;
                }
            })
            .into(imagePreview);
}

其他回答

我这样做的方式是启动一个线程,在后台下载图像,并为每个列表项传递一个回调。当图像下载完成后,它将调用回调,以更新列表项的视图。

然而,当您回收视图时,这种方法不太有效。

DroidParts的ImageFetcher需要零配置才能启动。

使用磁盘和内存中最近最少使用(LRU)缓存。高效解码图像。支持在后台线程中修改位图。具有简单的交叉褪色。具有图像加载进度回调。

例如,克隆DroidPartsGram:

Gilles Debonne的多线程性能教程。

这是来自Android开发者博客。建议的代码使用:

异步任务。一个硬的、有限大小的FIFO缓存。一个软的、易于垃圾收集的缓存。下载时可绘制的占位符。

您可以使用一些第三方库(如Piccaso或Volley)进行有效的延迟加载。您还可以通过实现以下内容创建自己的

用于从url下载图像的实现代码实现用于存储和检索图像的缓存机制(使用android的LruCache进行缓存)

这就是使用Jetpack Compose的方法。

implementation("io.coil-kt:coil-compose:1.3.1") // Add the Coil-Compose library
Image(
    painter = rememberImagePainter("https://www.example.com/image.jpg"),
    contentDescription = "My image description",
    modifier = Modifier.size(128.dp)
)

感谢nglauber和Gabriele Mariotti的回答。