androidandroid-resources

How to force the use of a string resource when there is more than one?


I have a string resource with the name app_name and the value My App Name. I only have a single strings.xml file, so my application only has one language and one default strings.xml file. The problem occurs when I import a library that has several resource strings with the same name (app_name) and other value (Library Name) for several languages such as Spanish and French. This causes all the places where I use app_name resource to return Library Name instead of My App Name when the language the user selects in the configurations is French or panish.

Obviously, I can change the name of the resource, but I prefer to keep that name and find a way to circumvent this behaviour. Is there a way to force Android to use a string resource even if there are others?


Solution

  • You're probably looking for the resConfigs gradle property.

    The Gradle resource shrinker removes only resources that are not referenced by your app code, which means it will not remove alternative resources for different device configurations. If necessary, you can use the Android Gradle plugin's resConfigs property to remove alternative resource files that your app does not need.

    For example, if you are using a library that includes language resources ..., then your app includes all translated language strings for the messages in those libraries whether the rest of your app is translated to the same languages or not. If you'd like to keep only the languages that your app officially supports, you can specify those languages using the resConfig property. Any resources for languages not specified are removed.

    Sample Gradle:

    defaultConfig {
        // Assuming your one strings file is English, keep that, remove all other languages
        resConfigs "en"
    }