11

On this page, it is written:

versionName — A string used as the version number shown to users. This setting can be specified as a raw string or as a reference to a string resource.

I would like to use a resource as version number. Something like @string/version .

What's the way ?

Thanks

Julien

Julien
  • 846
  • 1
  • 7
  • 19
  • You can check this if you have `productFlavour` on different variants and dimensions https://stackoverflow.com/questions/36105494/localizing-string-resources-added-via-build-gradle-using-resvalue – A S M Sayem Jul 14 '23 at 16:47

3 Answers3

5

I have create method using @Yaroslav's answer (https://stackoverflow.com/a/37432654/6711554). Here is code of setting package name from string file.

def getPackageName() {
  try {
     def stringsFile = file("./src/main/res/values/string.xml")
     return new XmlParser().parse(stringsFile).string.find { it.@name.equals 'your_package_name' }.text()
  }catch(e){
     println(e)
     return "default.packagename"
  }
}

and use it like

 applicationId getPackageName()

You can read any string in your gradle from your any resource file.

  • Are all this code entered into build.gradle? I cannot get it to work... I placed def at the top and replaced `applicationId "com.test.test` with `applicationId getPackageName()` – Sunkas Apr 13 '21 at 15:16
0

Try the following and sync your project with Gradle by clicking on the "Sync Now" button or by selecting "File" -> "Sync Project with Gradle Files" from the menu.

android {
    // ...

    defaultConfig {
        // ...
        resValue "string", "<your_variable_name>", '"@string/<your_string_resource_name>"'
    }
}
A S M Sayem
  • 2,010
  • 2
  • 21
  • 28
-1

There is a similar question, which is already answered - Android Gradle Read App Name from strings.xml. @SamuilYanovski offers to use configuration file like gradle.properties instead of trying to access Android resources from gradle file.

Community
  • 1
  • 1
Denis
  • 147
  • 4