尝试 jetpack compose 时,它​​显示错误:编译器后端,旧编译器无法加载

Sab*_* ks 22 android kotlin android-jetpack android-jetpack-compose

类 'androidx.compose.ui.platform.ComposeView' 由新的 Kotlin 编译器后端编译,旧编译器无法加载

这是我的 onCreate 方法:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return inflater.inflate(R.layout.fragment_delivered, container, false).apply {
        findViewById<ComposeView>(R.id.compose_view).setContent {
            MaterialTheme {
                Surface {
                    Text("Hello")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编写版本:

accompanistVersion = "0.1.9"
composeVersion = '0.1.0-dev17'
Run Code Online (Sandbox Code Playgroud)

应用程序.gradle

buildFeatures {
        compose true
        dataBinding true
    }
    composeOptions {
        kotlinCompilerVersion rootProject.kotlinVersion
        kotlinCompilerExtensionVersion rootProject.composeVersion
    }



// Compose
    implementation "androidx.compose.runtime:runtime:$rootProject.composeVersion"
    implementation "androidx.compose.ui:ui:$rootProject.composeVersion"
    implementation "androidx.compose.foundation:foundation:$rootProject.composeVersion"
    implementation "androidx.compose.foundation:foundation-layout:$rootProject.composeVersion"
    implementation "androidx.compose.material:material:$rootProject.composeVersion"
    implementation "androidx.compose.ui:ui-viewbinding:$rootProject.composeVersion"
    implementation "androidx.ui:ui-tooling:$rootProject.composeVersion"
    implementation "androidx.compose.runtime:runtime-livedata:$rootProject.composeVersion"
    implementation "com.google.android.material:compose-theme-adapter:$rootProject.composeVersion"
    implementation "dev.chrisbanes.accompanist:accompanist-coil:$rootProject.accompanistVersion"
Run Code Online (Sandbox Code Playgroud)

Blu*_*rer 18

请在您的 app/build.gradle 文件中添加此任务:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
    kotlinOptions {
        jvmTarget = "1.8"
        freeCompilerArgs += ["-Xallow-jvm-ir-dependencies", "-Xskip-prerelease-check"]
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 至于为什么需要这些编译器参数:虽然 Jetpack Compose 仍处于 alpha 阶段,但在使用新 IR 后端编译的依赖项以及使用尚未发布的类时,这些编译器参数可以抑制错误。(https://github.com/android/compose-samples/issues/120#issuecomment-681289777) (2认同)

Bry*_*yan 15

app/build.grade使用“Empty Compose Activity”创建新项目时,默认设置包括以下选项。

android {
    // other options

    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }

    // more options
}
Run Code Online (Sandbox Code Playgroud)

添加这些选项(特别是useIR = true)似乎为我修复了错误。


useIR选项引用了Kotlin的新 JVM 后端,其文档特别说明了以下内容。

如果您启用 Jetpack Compose,您将自动选择加入新的 JVM 后端,而无需在kotlinOptions.

这似乎是不正确的。


j0h*_*1_r 4

按照官方设置指南中的步骤进行操作导致我遇到了同样的问题。

为撰写库添加必要的依赖项/配置为我解决了这个问题。

  • tasks.withType 部分为我解决了这个问题。 (6认同)