# Android Gradle Extensions
###### tags: `Android Gradle`

[TOC]
# Introduction
As the name states, it is an extension to gradle. If we state variables, then we will be able to access them as we import this gradle extension to our **build.gradle**.
# How to create an gradle extension?
1. Create .gradle file in root Folder.
2. Apply/import .gradle file in build.gradle(:project)
3. Go to .gradle file
4. Add **ext {}**
5. Add the variables we want to use throughout our project and modules. Ex: dependencies version or versions we do not wish anyone to touch.
# Add constants/variables to gradle extension
Inside the **ext{}**, we will input the constants/variables. They can be either **array** or even **just variables with value**. See below example.
**.gradle file:**
We can use ext to add more variables for us to use in build.gradle file
```java=
ext {
def sdkMin = 16
def sdkTarget = 30
sdk_version = [
min : sdkMin,
target : sdkTarget
]
def defaultAppId = "com.zc.learngradle"
def defaultVersionCode = 1
def defaultVersionName = '1.0'
versionCode = defaultVersionCode
versionName = defaultVersionName
appId = defaultAppId
dependenciesVersion = [
constraintLayout : '2.0.4'
, appCompat : '1.3.0'
, androidMaterial : '1.4.0'
]
}
```
**Note:**
As it is a **gradle extension**, we can also use **def** to state the variables we want to use. Sometimes when the file gets longer, we might want to get them near the top to update them quicker.
# Add Gradle extension to build.gradle
Just go to the build.gradle that will be using the extensions and use **apply from: 'location'**. In this case, my gradle extension file was named **config.gradle** and location was on the **root folder**
```java=
apply from: '../config.gradle'
```
# Apply extensions in build.gradle
Application of the extension will differ on whether the extension value is in an array or not.
No matter which extension we apply, we use either **rootProject** or **project** to refer to the **ext (extension)**.
## Array value extension
```java=
project.ext.appId
```
## Single value extension
The name after **ext**, in this case sdk_version will refer to the array name, and the next one will refer to the key of the value inside array (target in this case).
```java=
project.ext.sdk_version.target
```
## Extension Application Example
>[color=orange]