Different string.xml files according to app Build Variants

5.7k views Asked by At

I want to assign a value to a string in string.xml different values depending on the Build Variant/buildType. I imagine something like this:

res/values-debug/string.xml
    <string name="my_string">some debug value</string>

res/values-release/string.xml
    <string name="my_string">some release value</string>

but I don't see anything like this out there. Is this possible?

4

There are 4 answers

3
just_user On BEST ANSWER

Yes it's possible!

In your build.gradle you can add something like this:

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        signingConfig signingConfigs.release
    }
    debug {
        applicationIdSuffix ".debug"
        minifyEnabled false
        debuggable true
        signingConfig signingConfigs.release
    }
}

Then in your src folder in your project you should have a folder called main, add one next to it called debug. Den as long as you are building your debug flavour any resources in your debug folder will replace those in main which is the release folder.

Should look like this:

src/
    main/
        java/ -- all your java code
        res/
            ...
            values/
                strings.xml
    debug/
        res/
            ...
            values/
                strings.xml

EDIT: The approaches from the two other answers works fine as well. But if you have a lot of strings keeping them as xml might be easier to handle.

0
John O'Reilly On
resValue 'string', '<string_name>', "some string"

define different ones in your build.gradle for different build variants/product flavors

2
Volodymyr On

It possible via your build.gradle file

buildTypes {
    release {
        resValue "string", "my_string", "some release value"
    }
    debug {
        resValue "string", "my_string", "some debug value"
    }
}

Then you can just use this value like @string/my_string where you want

0
Nicola Gallazzi On

You can do it directly from Android Studio. For example, if you need a different app name for your "staging" flavor, you can (Android Studio v3.5):

  • Right click on values folder -> New -> Values resource file
  • Select "staging" in the source set menu
  • specify strings.xml as filename

At this point Android Studio generates an additional strings.xml file for your particular build variant. Edit the created file with your "staging" app name (E.g. MyAppName - Staging)

strings.xml - staging strings.xml - production

build.gradle(app)

productFlavors {
        stage {
            applicationIdSuffix ".staging"
            buildConfigField 'String', 'SITE_URL', '"[staging_link_here]"'
        }
        prod {
            buildConfigField 'String', 'SITE_URL', '"[production_link_here]"'
        }
 }