如何让所有Android Studio项目默认包含指定共享依赖?
如何让Android新建项目默认包含指定依赖库
方法一:修改Android Studio内置项目模板
直接修改AS自带的新建项目模板,让默认生成的build.gradle自动包含所需依赖:
- 找到AS的模板目录:
- Windows:
C:\Program Files\Android\Android Studio\plugins\android\lib\templates\projects\NewAndroidProject - macOS:
/Applications/Android Studio.app/Contents/plugins/android/lib/templates/projects/NewAndroidProject - Linux:
/usr/local/android-studio/plugins/android/lib/templates/projects/NewAndroidProject
- Windows:
- 进入该目录下的
template/app文件夹,打开build.gradle.ftl文件 - 在
dependencies代码块中添加你需要的依赖,比如Navigation库:dependencies { // 原有默认依赖 implementation 'androidx.core:core-ktx:1.12.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.11.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' // 自定义依赖示例 implementation 'androidx.navigation:navigation-fragment-ktx:2.7.7' implementation 'androidx.navigation:navigation-ui-ktx:2.7.7' } - 保存文件后重启Android Studio,后续新建项目时这些依赖会自动出现在app模块的build.gradle中
注意:Android Studio更新时,内置模板可能被覆盖,建议提前备份修改后的文件。
方法二:创建自定义项目模板
如果不想修改内置模板,可创建自己的模板复用:
- 先创建一个包含所有所需依赖、配置的示例项目,确保能正常构建
- 点击
File > Export to Template,填写模板名称、描述,选择需要包含的文件后完成导出 - 之后新建项目时,在
New Project界面就能看到你的自定义模板,选择它即可生成带预设依赖的项目
附加:解决IP限制导致的依赖下载问题
可在模板的根build.gradle中配置国内镜像源,让新建项目默认使用:
打开模板目录下的root/build.gradle.ftl文件,修改repositories块:
buildscript { repositories { maven { url 'https://maven.aliyun.com/repository/public' } google() mavenCentral() } // ... } allprojects { repositories { maven { url 'https://maven.aliyun.com/repository/public' } google() mavenCentral() } }
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

