Localizing string resources added via build.gradle using "resValue"

AndroidMechanic - Viral Patel picture AndroidMechanic - Viral Patel · Mar 19, 2016 · Viewed 9.2k times · Source

This is in continuation to an answer which helped me on this post

We can add the string resource as follows from build.gradle:

productFlavors {
    main{
        resValue "string", "app_name", "InTouch Messenger"
    }

    googlePlay{
        resValue "string", "app_name", "InTouch Messenger: GPE Edition"
    }
}

It works like a charm and serves the purpose of having different app names per flavor. (with the original app_name string resource deleted from strings.xml file.

But, how do we add localized strings for this string resource added from build.gradle ?

Is there an additional parameter we can pass specifying the locale? OR Possible to do it using a gradle task?

Note: I cannot do this using strings.xml (not feasible because of several ways in which my project is structured)

Answer

TWiStErRob picture TWiStErRob · Mar 29, 2016

My other answer about the generated resources may be an overkill for you use case though. Base what I currently know about your project I think this one is a better fit: (not that you can still combine this with generated resources)

src/flavor1/res/values/strings.xml

<string name="app_name_base">InTouch Messenger"</string>
<string name="app_name_gpe">InTouch Messenger: GPE Edition"</string>

src/flavor1/res/values-hu/strings.xml

<string name="app_name_base">InTouch Üzenetküldő"</string>
<string name="app_name_gpe">InTouch Üzenetküldő: GPE Változat"</string>

src/flavor2/res/values/strings.xml

<string name="app_name_base">Whatever Messenger"</string>
<string name="app_name_gpe">Whatever Messenger: GPE Edition"</string>

src/flavor2/res/values-hu/strings.xml`

<string name="app_name_base">Whatever Üzenetküldő"</string>
<string name="app_name_gpe">Whatever Üzenetküldő: GPE Változat"</string>

build.gradle

android {
    sourceSets {
        [flavor1, flavor3].each {
            it.res.srcDirs = ['src/flavor1/res']
        }
        [flavor2, flavor4].each {
            it.res.srcDirs = ['src/flavor2/res']
        }
    }
    productFlavors { // notice the different numbers than sourceSets
        [flavor1, flavor2].each {
            it.resValue "string", "app_name", "@string/app_name_base"
        }
        [flavor3, flavor4].each {
            it.resValue "string", "app_name", "@string/app_name_gpe"
        }
    }
}

This means that flavor1/2 will have an extra unused app_name_gpe string resource, but that'll be taken care of by aapt:

android {
    buildTypes {
        release {
            shrinkResources true // http://tools.android.com/tech-docs/new-build-system/resource-shrinking
        }