尝试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")
                }
            }
        }
    }
}

撰写版本:

accompanistVersion = "0.1.9"
composeVersion = '0.1.0-dev17'

app.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"

解决方法

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

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

在创建带有“空撰写活动”的新项目时,默认的app/build.grade包含以下选项。

android {
    // other options

    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }

    // more options
}

添加这些选项(特别是useIR = true)似乎可以解决我的错误。


useIR选项引用了Kotlin的new JVM backend,文档中对此有特别说明。

如果启用Jetpack Compose,您将自动选择加入新的JVM后端,而无需在kotlinOptions中指定编译器选项。

这看似不正确。

,

按照official setup guide中的步骤进行操作会导致我遇到相同的问题。

添加必要的dependencies/configuration for the compose library为我解决了此问题。

,

.kts版本

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "1.8"
    kotlinOptions.freeCompilerArgs = listOf(
        *kotlinOptions.freeCompilerArgs.toTypedArray(),"-Xallow-jvm-ir-dependencies","-Xskip-prerelease-check")
    useIR = true
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...