Compose Multiplatform中AnimatedImage在Android端报NoClassDefFoundError求助
解决Compose Multiplatform AnimatedImage Android端崩溃问题
问题原因
loadResourceAnimatedImage内部依赖了桌面端Compose UI库的Resources_desktopKt类,该类在Android端不存在,导致运行时抛出NoClassDefFoundError。
解决方案
改用跨平台兼容的资源读取逻辑,避免直接使用桌面端专属的loadResourceAnimatedImage API:
1. 定义跨平台资源读取接口
在common模块中添加expect函数:
expect fun getResourceBytes(path: String): ByteArray?
2. 实现各平台的资源读取
- Desktop模块:
actual fun getResourceBytes(path: String): ByteArray? { return object {}.javaClass.classLoader.getResourceAsStream(path)?.readBytes() }
- Android模块:
import android.content.Context import androidx.compose.ui.platform.LocalContext actual fun getResourceBytes(path: String): ByteArray? { val context = LocalContext.current val resourceName = path.removePrefix("drawable/").removeSuffix(".gif") val resId = context.resources.getIdentifier(resourceName, "drawable", context.packageName) return if (resId != 0) { context.resources.openRawResource(resId).readBytes() } else null }
3. 修改GIF加载代码
更新Pony组件,使用新的资源读取方式加载GIF:
@Composable fun Pony() { val animatedImage = loadOrNull { getResourceBytes("drawable/pony.gif")?.let { loadAnimatedImage(it) } }?.animate() ?: ImageBitmap.Blank Image( animatedImage, contentDescription = null, Modifier.size(100.dp) ) }
内容的提问来源于stack exchange,提问作者maiatoday
相关产品推荐
相关产品推荐

