Jetpack Compose集成Hilt后出现NoSuchMethodError setContent错误求助
解决方案
该报错的核心原因是Jetpack Compose、Kotlin、Hilt、Android Gradle Plugin之间的版本不兼容,按以下步骤修改即可解决:
1. 替换项目级build.gradle配置
将不稳定的alpha版AGP和旧版Hilt插件替换为匹配的稳定版本:
buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.0.4' classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5' } } task clean(type: Delete) { delete rootProject.buildDir }
2. 统一settings.gradle版本
修正Kotlin和AGP的版本,和项目级配置保持一致:
pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() } plugins { id 'com.android.application' version '7.0.4' id 'com.android.library' version '7.0.4' id 'org.jetbrains.kotlin.android' version '1.5.31' } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } } rootProject.name = "ExampleApp" include ':app'
3. 修改模块级build.gradle配置
3.1 修正plugins配置
移除kapt的重复版本声明,继承settings.gradle中统一的Kotlin版本:
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id "org.jetbrains.kotlin.kapt" id 'dagger.hilt.android.plugin' }
3.2 修正Compose编译器配置
匹配Compose稳定版对应的编译器版本,删除单独的compiler依赖:
composeOptions { kotlinCompilerExtensionVersion "1.0.5" }
3.3 修正依赖配置
升级匹配的依赖版本,删除已废弃的Hilt依赖:
dependencies { implementation 'androidx.core:core-ktx:1.6.0' implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.0' // Hilt implementation 'com.google.dagger:hilt-android:2.40.5' kapt 'com.google.dagger:hilt-compiler:2.40.5' kapt 'androidx.hilt:hilt-compiler:1.0.0' // Lifecycle implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1" implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.1' implementation "androidx.fragment:fragment-ktx:1.3.6" // Coroutines implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1' // Compose implementation 'androidx.compose.ui:ui:1.0.5' implementation 'androidx.compose.ui:ui-tooling:1.0.5' implementation 'androidx.compose.foundation:foundation:1.0.5' implementation 'androidx.compose.material:material:1.0.5' implementation 'androidx.compose.material:material-icons-core:1.0.5' implementation 'androidx.compose.material:material-icons-extended:1.0.5' implementation 'androidx.activity:activity-compose:1.4.0' implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' }
4. 补充Hilt必填配置
你需要新增自定义Application类,添加Hilt注解,否则Hilt无法正常初始化:
@HiltAndroidApp class MyApp: Application()
并在AndroidManifest.xml的application标签中新增配置:
android:name=".MyApp"
5. 清理缓存重建
执行Android Studio菜单栏 File -> Invalidate Caches / Restart,重启后重新执行build即可。
内容的提问来源于stack exchange,提问作者apleuxa12
相关产品推荐
相关产品推荐

