Is it possible to define an Android string-array resource in Gradle?

后端 未结 4 2357
被撕碎了的回忆
被撕碎了的回忆 2021-01-04 17:50

In Gradle for Android, I\'m trying to generate the equivalent of this string-array resource...


    
         


        
4条回答
  •  醉酒成梦
    2021-01-04 18:24

    To be able to create array via resValue you shoul store all array elements inside item tag. So you should write in gradle something like this:

    resValue('array', 'ver_2_skus', "sku1sku2")
    

    But there is an awful bug - all < symbols writes to res as <. I spend some time to find how can I write < with gradle, but failed. So I made one hack - I replace < with some string and then, after build, replace it with <. I hate this hack, maybe I miss something, but it works. Here is code, that you must put to the end of gradle script (yes, code must be duplicated to work).

    1. While create an res array replace all < with some string, i.e. IWANTTOREPLACEITWITHLEFTARROW:
    resValue('array', 'ver_2_skus', "IWANTTOREPLACEITWITHLEFTARROWitem>sku1IWANTTOREPLACEITWITHLEFTARROW/item>IWANTTOREPLACEITWITHLEFTARROWitem>sku2IWANTTOREPLACEITWITHLEFTARROW/item>")
    
    1. Add this to the end of gradle file:
    android.applicationVariants.all { variant ->
        println("variant: "+variant.dirName)
        variant.mergeResources.doLast {
            try {
                println("3")
                ext.env = System.getenv()
                File valuesFile = file("${buildDir}/intermediates/res/merged/${variant.dirName}/values/values.xml")
                String content = valuesFile.getText('UTF-8')
                content = content.replaceAll(/IWANTTOREPLACEITWITHLEFTARROW/, '<')
                valuesFile.write(content, 'UTF-8')
            } catch (Exception e) {
                println("Exception = " + e)
            }
        }
    
        try {
            println("try")
            ext.env = System.getenv()
            File valuesFile = file("${buildDir}/intermediates/res/merged/${variant.dirName}/values/values.xml")
            String content = valuesFile.getText('UTF-8')
            content = content.replaceAll(/IWANTTOREPLACEITWITHLEFTARROW/, '<')
            valuesFile.write(content, 'UTF-8')
        } catch (Exception e) {
            println("Exception = " + e)
        }
    }
    

提交回复
热议问题