get the application's resources languages

后端 未结 11 1121
庸人自扰
庸人自扰 2020-12-02 23:30

Is it possible, at runtime, to know which resources languages are embedded in my app?

i.e the presence of this folders:

values-en
values-de
values-fr         


        
11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 00:31

    For anyone using Gradle, I did it like so below it traverses all strings.xml, grabs the directory names and figures out the locales from there. It adds a String[] to BuildConfig which you can access as BuildConfig.TRANSLATION_ARRAY

    task buildTranslationArray << {
        def foundLocales = new StringBuilder()
        foundLocales.append("new String[]{")
    
        fileTree("src/main/res").visit { FileVisitDetails details ->
            if(details.file.path.endsWith("strings.xml")){
                def languageCode = details.file.parent.tokenize('/').last().replaceAll('values-','').replaceAll('-r','-')
                languageCode = (languageCode == "values") ? "en" : languageCode;
                foundLocales.append("\"").append(languageCode).append("\"").append(",")
            }
        }
    
        foundLocales.append("}")
        //Don't forget to remove the trailing comma
        def foundLocalesString = foundLocales.toString().replaceAll(',}','}')
        android.defaultConfig.buildConfigField "String[]", "TRANSLATION_ARRAY", foundLocalesString
    
    }
    preBuild.dependsOn buildTranslationArray
    

    So after the above task occurs (on prebuild) the BuildConfig.TRANSLATION_ARRAY has your list of locales.

    I'm not a Gradle/Groovy expert so this could definitely be a bit neater.

    Reasoning - I ran into too many issues implementing pawelzieba's solution, I had no reliable strings to 'compare' as the translations were crowdsourced. The easiest way then was to actually look at the values-blah folders available.

提交回复
热议问题