按谷歌官方教程启用Safe Args失败:Gradle配置项缺失
解决Android Safe Args启用配置问题
一、根目录build.gradle配置
你的根目录构建文件采用新的Plugins DSL格式,无需buildscript块,直接在plugins块中添加Safe Args的classpath即可,注意版本要与你当前使用的Navigation版本(2.4.1)保持一致:
// Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { id 'com.android.application' version '7.4.0' apply false id 'com.android.library' version '7.4.0' apply false id 'org.jetbrains.kotlin.android' version '1.7.21' apply false // 添加Safe Args依赖,版本匹配Navigation版本 id 'androidx.navigation.safeargs.kotlin' version '2.4.1' apply false }
二、模块级app/build.gradle配置
同样使用Plugins DSL格式,直接在plugins块中引入Safe Args插件:
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' // 启用Safe Args插件 id 'androidx.navigation.safeargs.kotlin' } // 以下为原有配置,保持不变 android { namespace 'com.example.myfirstapp' compileSdk 33 defaultConfig { applicationId "com.example.myfirstapp" minSdk 24 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { viewBinding true } } dependencies { implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.9.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.navigation:navigation-fragment-ktx:2.4.1' implementation 'androidx.navigation:navigation-ui-ktx:2.4.1' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' }
三、解决"unable to resolve class val"报错
按以下步骤排查修复:
- 配置完成后,点击Android Studio右上角的Sync Project with Gradle Files按钮同步项目
- 确保导航图中已正确设置参数,然后执行Build -> Make Project重新构建
- 检查代码中是否正确导入了Safe Args生成的导航类(例如从FragmentA导航到FragmentB时,生成的类为
FragmentADirections.actionFragmentAToFragmentB(参数))
内容的提问来源于stack exchange,提问作者define_makefile
相关产品推荐
相关产品推荐

