Search code examples
androidgradlepreprocessor

Replace word in strings.xml with gradle for a buildType


I have a project which has multiple localizations.
Now I have to replace a certain word in all strings.xml files for different buildTypes. For example let's say I have this:

<string>My name is Bill</string>
<string>Bill is on duty today</string>

And in another buildType I need to have

<string>My name is Will</string>
<string>Will is on duty today</string>

How can I do it (probably through Gradle)?


Solution

  • Ok, found a correct solution, which is not a workaround: For the required buildType add the following

        applicationVariants.all { variant ->
        variant.mergeResources.doLast {
            def dir = new File("${buildDir}/intermediates/res/merged/${variant.dirName}")  //iterating through resources, prepared for including to APK (merged resources)
            println("Resources dir " + dir)
            dir.eachFileRecurse { file ->
                if(file.name.endsWith(".xml")) { //processing only files, which names and with .xml
                    String content = file.getText('UTF-8')
                    if(content != null && content.contains("Bill")) {
                        println("Replacing name in " + file)
                        content = content.replace("Bill", "Will")  //replacing all Bill words with Will word in files
                        file.write(content, 'UTF-8')
                    }
    
                }
            }
        }