由於組件化實踐中模塊比較多,因此配置gradle,添加依賴庫時,需要考慮簡化工作。
第一步:在Project目錄下點擊鼠標右鍵,依次new——>File
第二步:然後輸入統一配置文件的名稱,以.gradle結尾
第三步:在新建的統一配置文件fjs.gradle裏面配置要管理的項,代碼如下所示
ext{
isApplication = false //false:作爲Lib組件存在, true:作爲application存在
android = [
compileSdkVersion :28,
buildToolsVersion :"29.0.0",
minSdkVersion :15,
targetSdkVersion :28,
versionCode :1,
versionName :"1.0"//必須是int或者float,否則影響線上升級
]
version = [
androidSupportSdkVersion:"28.0.0",
]
dependencies = [
"appcompat-v7":"com.android.support:appcompat-v7:${version["androidSupportSdkVersion"]}",
]
}
第四步:在project目錄下的build.gradle裏添加下面一句話
apply from: "fjs.gradle"
build.gradle完整代碼如下所示:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply from: "fjs.gradle"
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
第五步:在模塊裏使用ext來統一配置,如在app目錄下的build.gradle裏面使用,代碼如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.android["compileSdkVersion"]
buildToolsVersion rootProject.ext.android["buildToolsVersion"]
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion rootProject.ext.android["minSdkVersion"]
targetSdkVersion rootProject.ext.android["targetSdkVersion"]
versionCode rootProject.ext.android["versionCode"]
versionName rootProject.ext.android["versionName"]
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
api rootProject.ext.dependencies["appcompat-v7"]
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
最後點擊Sync Now
結果如下所示:
統一配置文件是爲了讓各個模塊的各個參數達到一致,利於以後統一修改、管理。