Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 202
Vladyslav Matviienko Avatar asked Nov 28 '16 11:11

Vladyslav Matviienko


3 Answers

You can do something like following in build.gradle but would only apply to that particular string resource.

resValue "string", "<string_name>", string_value

like image 188
John O'Reilly Avatar answered Nov 20 '22 08:11

John O'Reilly


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')
                }

            }
        }
    }
like image 3
Vladyslav Matviienko Avatar answered Nov 20 '22 08:11

Vladyslav Matviienko


The answers here no longer work with latest android build tools, but here is a new version that is working for me.

android.applicationVariants.all { variant ->
    variant.mergeResources.doFirst {
         variant.sourceSets.each { sourceSet ->
            sourceSet.res.srcDirs = sourceSet.res.srcDirs.collect { dir ->
                def relDir = relativePath(dir)
                copy {
                    from(dir)
                    include '**/*.xml'
                    filteringCharset = 'UTF-8'
                    filter {
                        line -> line
                                .replace('Bill', 'Will')
                    }
                    into("${buildDir}/tmp/${variant.dirName}/${relDir}")
                }
                copy {
                    from(dir)
                    exclude '**/*.xml'
                    into("${buildDir}/tmp/${variant.dirName}/${relDir}")
                }
                return "${buildDir}/tmp/${variant.dirName}/${relDir}"
            }
        }
    }
}
like image 2
mcfedr Avatar answered Nov 20 '22 10:11

mcfedr