app目录下的gradle文件怎样引用project目录下的自定义gradle文件

在android开发中经常会操作app以及同级model中的build.gradle文件,有些配置会重复写,我们可不可以在project的目录下新建一个gradle文件来统一管理呢?

当然可以,提供demo如下,仅供参考。

1.demo中需要用到的几个文件截图如下

 2.编写自己需要的gradle文件,如:version.gradle

ext.target = [:]

def version = [:]
version.appcompat = "1.2.0"
version.material = "1.2.1"
version.constraintlayout = "2.0.1"
version.greendao = "3.3.0"
version.generator = "3.3.0"

def target =[:]
target.appcompat = "androidx.appcompat:appcompat:$version.appcompat"
target.material = "com.google.android.material:material:$version.material"
target.constraintlayout = "androidx.constraintlayout:constraintlayout:$version.constraintlayout"
target.greendao = "org.greenrobot:greendao:$version.greendao"
target.generator = "org.greenrobot:greendao-generator:$version.generator"

ext.target = target

def build_version = [:]
build_version.compile_sdk = 30
build_version.build_tools = "30.0.3"
build_version.min_sdk = 16
build_version.target_sdk = 30
build_version.version_code = 1
build_version.version_name = "1.0"
ext.build_version = build_version

3.在项目中的build.gradle文件中引入version.gradle文件

buildscript {
    apply from: 'version.gradle'
}

4.在app的build.gradle总使用如下:

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion build_version.compile_sdk
    buildToolsVersion build_version.build_tools

    defaultConfig {
        applicationId "com.sun.test"
        minSdkVersion build_version.min_sdk
        targetSdkVersion build_version.target_sdk
        versionCode build_version.version_code
        versionName build_version.version_name
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation target.appcompat
    implementation target.material
    implementation target.constraintlayout
}

 

posted on 2021-11-09 14:50  HarperSun  阅读(875)  评论(0编辑  收藏  举报

导航