Skip to content

Instantly share code, notes, and snippets.

@NamtarR
Last active February 12, 2023 07:53
Show Gist options
  • Save NamtarR/1552eae0d6a549a6a3c629098122b233 to your computer and use it in GitHub Desktop.
Save NamtarR/1552eae0d6a549a6a3c629098122b233 to your computer and use it in GitHub Desktop.
Android resource generation task
apply from: './task.gradle'
android.applicationVariants.all { variant ->
def file = project.file("build/generated/res/res-task/main")
def files = project.files(file)
files.builtBy(generateStringsFile)
variant.registerGeneratedResFolders(files)
}
{
"resource_generator_title": "Resource generation",
"resource_generator_description": "Strings for this app are generated at build time from input_file.json",
"resource_generator_action": "Learn more",
"resource_generator_url": "https://namtarr.com"
}
import groovy.json.JsonSlurper
import groovy.xml.MarkupBuilder
task generateStringsFile {
def inputFile = project.rootProject.file("input_file.json")
def outputFile = project.file("build/generated/res/res-task/main/values/strings.xml")
doLast {
outputFile.parentFile.mkdirs()
outputFile.withWriter("UTF-8") { writer ->
def json = new JsonSlurper().parseText(inputFile.text)
def xml = new MarkupBuilder(new IndentPrinter(writer, " ", true, true))
def mkp = xml.getMkp()
xml.setDoubleQuotes(true)
mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
mkp.comment("Generated at ${new Date()}")
mkp.yield "\r\n"
xml.resources {
json.each { key, value ->
string(name: key) { mkp.yield(value) }
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment