You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Safe Args实现Fragment间传值的Gradle正确配置方法

问题根因
  • 项目使用Android Gradle Plugin 7.1.3默认的plugins DSL配置结构,旧版buildscript+apply plugin写法适配不当、放置位置错误都会直接触发Gradle报错
  • 此前尝试添加的Safe Args插件版本为2.3.3,和模块内已引入的2.5.0版本Navigation组件版本不匹配,版本冲突会直接导致编译失败
  • Safe Args需要同时完成项目级、模块级两级Gradle配置,缺省任意环节都无法正常生效
正确配置步骤

1. 修改项目根目录下的build.gradle

在根级plugins块中添加Safe Args插件声明,插件版本必须和项目中使用的Navigation组件版本保持完全一致,不需要额外添加buildscript块配置:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.3' apply false
    id 'com.android.library' version '7.1.3' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.21' apply false
    // 新增Safe Args插件声明
    id 'androidx.navigation.safeargs.kotlin' version '2.5.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

2. 修改app模块目录下的build.gradle

在模块级plugins块中直接引入Safe Args插件,不需要额外写apply plugin语句,也不需要重复声明版本:

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    // 新增Safe Args插件引入
    id 'androidx.navigation.safeargs.kotlin'
}

// 其余android、dependencies配置保持原有内容即可,无需修改
注意事项
  • 不要混用旧版buildscript { classpath ... }配置和新版plugins DSL配置,按照当前项目结构使用上述DSL写法即可,不需要额外添加classpath依赖
  • 后续如果升级Navigation组件版本,必须同步修改根目录下声明的Safe Args插件版本,保证两者版本号完全一致
  • 配置完成后点击Gradle Sync按钮等待同步完成,即可正常使用Safe Args生成的跳转Directions类、参数Args类实现Fragment传参

内容的提问来源于stack exchange,提问作者Alex20280

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 04:45:38