Reference build.gradle versionName attribute in xml layout

According to http://tools.android.com/tech-docs/new-build-system you can create resources directly from gradle, so putting

android {
...
    defaultConfig {
        applicationId "se.test.myapp"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    ...
    applicationVariants.all { variant ->    
        variant.resValue "string", "versionName", variant.versionName
    }
    ...
}

in your build.gradle will do the trick

It creates resource file generated.xml during compilation in generated/res folder which is included alongside with resources provided by you in values folder. So you can use android:text="@string/versionName" to reference this value. Unfortunately, sometimes IDE can't resolve this reference, so it'll look like an error in your layout resource (while it's a valid statement and will be resolved at runtime).

You can suppress the error by clicking inside the "@string/versionName", then Alt+Enter, in the menu select "Create string value resource 'versionName", then "Suppress for tag".


Edit: You should not use Jack only for this. As per the official announcement Jack is deprecated (for everything except Java 8 features).

I used a string resource:

<resources>
    <string name="app_ver" translatable="false">1.0.2</string>
    ...
</resources>

in the app's build.gradle:

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        ...
        versionName "@string/app_ver"
        jackOptions {
            enabled true        
        }
    }
...
}

And like this:

<Preference
    android:title="Version"
    android:summary="@string/app_ver"/>

This project in GitHub contains a working version of this.


I use variables in my projects for versionName and versionCode

for example, in the app's build.gradle:

final VERSION_NAME = '2.2.3'
final VERSION_CODE = 15

android {
    defaultConfig {
        resValue "string", "version_code", VERSION_NAME + " (build " + VERSION_CODE + ")"
        versionCode VERSION_CODE
        versionName VERSION_NAME
        ...
    }
...
}

Android Studio automatically generates an untranslatable string resource:

<string name="version_code" translatable="false">2.2.3 (build 15)</string>

which I can use in xml:

<Preference
    android:selectable="false"
    android:title="@string/version"
    android:summary="@string/version_code" />

hope it will be useful

Tags:

Android