这是一个典型的 Compose Multiplatform 资源加载问题。当从 Android 原生模块调用 KMP 共享模块时,资源文件可能没有被正确打包到 APK 中。以下是几个可能的解决方案:
1. 检查 Android 模块的依赖配置
在你的 Android 模块的 build.gradle.kts 中,确保正确依赖了共享模块:
dependencies {
implementation(project(":shared"))
// 确保添加了 Compose Resources 依赖
implementation("org.jetbrains.compose.runtime:runtime-android:$compose_version")
implementation("org.jetbrains.compose.foundation:foundation-android:$compose_version")
}
2. 在共享模块配置资源
确保在共享模块的 build.gradle.kts 中正确配置了资源:
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
@OptIn(ExperimentalComposeLibrary::class)
implementation(compose.components.resources)
}
}
val androidMain by getting {
dependencies {
implementation("androidx.compose.ui:ui-tooling-preview")
}
}
}
}
android {
sourceSets["main"].resources.srcDirs("src/commonMain/composeResources")
}
3. 添加 ProGuard/R8 规则
在 Android 模块的 proguard-rules.pro 中添加:
-keep class org.jetbrains.compose.resources.** { *; }
-keepclassmembers class * {
@org.jetbrains.compose.resources.* <methods>;
}
-keep class **.inputdemo.shared.generated.resources.** { *; }
4. 确保资源同步
在项目根目录运行以下命令重新生成资源:
./gradlew :shared:generateComposeResClass
./gradlew clean
./gradlew assembleDebug
5. 检查资源路径
确保资源文件位于正确的路径:
shared/src/commonMain/composeResources/drawable/compose_multiplatform.xml
6. 在 Android 模块初始化资源
如果以上方法都不奏效,可以尝试在 Android 模块的 Application 类中手动初始化资源:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// 初始化 Compose Resources
System.setProperty(
"compose.resources.dir",
context.filesDir.absolutePath
)
}
}
7. 使用 Android 资源作为临时方案
如果问题仍然存在,可以暂时将资源文件复制到 Android 模块:
// 在 Android 模块中创建相同的资源
// app/src/main/res/drawable/compose_multiplatform.xml
// 然后在代码中使用条件编译
expect fun getComposeMultiplatformDrawable(): DrawableResource
// Android 实现
actual fun getComposeMultiplatformDrawable(): DrawableResource {
return DrawableResource("drawable/compose_multiplatform.xml")
}
最可能的原因是 Android 模块没有正确包含共享模块的资源。建议先尝试方案 1-4,特别是检查依赖配置和添加 ProGuard 规则。