From the course: Android Studio Essential Training 2020

Manage dependency version variables

From the course: Android Studio Essential Training 2020

Start my 1-month free trial

Manage dependency version variables

- [Narrator] Gradle build files can use variables to represent strings. This is particularly useful when you're managing software library versions. If you have two or more dependencies, that all depend on a single version, and those versions all move together, you can declare the version once as a variable and then refer to that variable wherever you need it. You can define variables either in the module level gradle file or in the project file but the syntax is different. I'll start with defining a variable right here in the dependencies block in the modules file. Let's say I wanted to manage the gson version. I'll take this version number 2.8.6 and then above my implementation line I'll add a new line and I'll start with, def, for define and then I can make up my own variable name. I'll call this gson_version and then I'll wrap this version in double quotes. Now, I can come down here and change this version to the variable that always starts with a dollar sign, I'll type in the version, and I'll see an error indicator. The error indicator is telling me that if I want to use a variable I have to use double quotes. So I'll change this from single to double quotes, and then I'll re-sync and if everything works okay, it should be fine. My version's now defined in that variable. This syntax is perfect if you're only using a particular dependency in one module. If you're working in a multi-module project though, and if multiple modules are referring to the same library, you might want to define your variables at the project level Here's how you do that. I'll select this line and copy it to the clipboard, and then I'm going to comment it out with a double slash at the beginning of the line. Then I'll go to my project build file, and I'll paste that code in, but instead of using def this time I'll use ext. And this means the same thing, I'm creating the variable but now it's a project wide variable. I'll click sync now again and if everything works as expected the project once again compiles, and the version number is accepted. So that's how you can use gradle variables to manage library versions either locally in the modules version of the gradle build file or globally in the projects version

Contents