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
Try calling AssetManager.getLocales():
Get the locales that this asset manager contains data for.
Or you can try if you can get a list using list().
Return a String array of all the assets at the given path.
Inspired by Mendhak's solution I created something a bit cleaner:
defaultConfig {
....
def locales = ["en", "it", "pl", "fr", "es", "de", "ru"]
buildConfigField "String[]", "TRANSLATION_ARRAY", "new String[]{\""+locales.join("\",\"")+"\"}"
resConfigs locales
}
Then in Java use:
BuildConfig.TRANSLATION_ARRAY
Advatages of this method:
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.
Are you talking about this?
String language = Locale.getDefault().getDisplayLanguage();
Do you mean:
String[] locales = getAssets().getLocales();
This would let you get the language that your device have.