Android Studio ——How can I modify one Class's field before compile by build.gradle

280 Views Asked by At

In my Android App that I'm developing with Android Studio, I have a class:

public class Config
{
  public static final String SDK_VERSION = "0.1";
}

I want to modify the value of the SDK_VERSION field by changing the file build.gradle:

def SDK_VERSION = "0.1"

android
{
  defaultConfig {
      versionName SDK_VERSION
  }
}

How can I make the value of SDK_VERSION in Config.java change automatically when I change it in build.gradle? Otherwise, I might change one but forget to change the other.

1

There are 1 best solutions below

2
On

You can do it for example in the your starter Activity in onCreate(), but make in not final befor.

Config.sdk_version = BuildConfig.VERSION_NAME;

Or why don't just use BuildConfig.VERSION_NAME; instead in the place where this constant is needed?