I would like to show user contents of notifications that dispatched from this app since the app had been started.
This app is creating for my learning.

它使用LazyColumn Compose,但在有很多通知的情况下速度非常慢.

Probably it caused by taking long time to load drawable from Notification LargeIcon.
I want to load it asynchronously but I have no idea how should I do it in compose.

以下是LazyList项的部分代码.

@Composable
fun ListElement(notify: Notification) {
    val drawableState = remember {mutableStateOf<Drawable?>(null)}
    Row(modifier=Modifier.height(80.dp).fillMaxWidth().padding(start=10.dp, top=2.dp, bottom=0.dp, end=10.dp), horizontalArrangement = Arrangement.SpaceBetween) {
        Column {
            Text(
                notify.extras.getString(Notification.EXTRA_TITLE, ""),
                style = MaterialTheme.typography.titleMedium
            )
            Text(notify.extras.getString(Notification.EXTRA_TEXT, ""))
        }
        val icon = notify.getLargeIcon()
        if (icon != null) {
            icon.loadDrawableAsync(context=LocalContext.current, listener=(Icon.OnDrawableLoadedListener { d -> drawableState.value = d }), handler= Handler())
    // I have no idea how to load asynchronously...
            if (drawableState.value != null) {
                val bitmap = drawableState.value!!.toBitmap()
                Spacer(modifier = Modifier.height(10.dp))
                Image(
                    bitmap = bitmap.asImageBitmap(),
                    contentDescription = "Icon",
                    modifier = Modifier.fillMaxHeight()
                )
            }
        }}
}

推荐答案

最好不要重新发明轮子,而是使用100或Fresco等库来处理异步图像加载.

下面是一个如何使用Coil从LazyColumn中的Icon异步加载可绘制内容的示例.这将在加载图像时显示占位符图标,然后在图像可用时用加载的图像替换占位符.

LazyColumn {
    items(data) { item ->
        val icon = Icon(item.icon)
        val painter = rememberImagePainter(item.imageUrl)

        Image(
            painter = painter,
            contentDescription = null
        ) {
            if (painter.isLoading) {
                Icon(icon)
            } else {
                it()
            }
        }
 }

不要忘记导入此库:

io.coil-kt:coil-compose:2.5.0"

Android相关问答推荐

RemoteActivityHelper.startRemoteActivity不适用于Android Wear OS 4模拟器

如何更新Kotlin中的显示?

如何从URI中获取图像大小

Android写/读二进制文件到共享存储

更改选定的切换轨道 colored颜色

Android 中 recyclerview 的自定义分隔线 colored颜色 不起作用

Gradle在我的Android Compose项目中继续推广依赖版本

Kotlin Multiplatform Mobile targetSdk 已弃用

React-native 3D对象渲染

在 Jetpack Compose 的无状态 Compose 中管理条件逻辑

如何使用 Jetpack Compose 制作两个圆圈

Hilt 依赖注入重复绑定错误

如何在 Android 应用中录制短视频?

Android Material Date Range Picker - 如何仅更改所选范围日期的文本 colored颜色 ?

如何在 Jetpack Compose 中填充矢量图像的背景?

在 android-billing-5.0 中获取 ProductDetails 价格

如何将 Android Studio 与模拟器连接起来

Android 模拟器没有响应 Xamarin 的 AMD 进程的问题

Android 视图阴影

我可以更改 Android startActivity() 过渡动画吗?