I'm doing a project where there's a search feature, but only enabled if the labels searched for are translated in the device's language. Is there any way to check if a resource exist in a specific locale? I want to avoid hard coding which translations are available.
Based on the commented links, I think this is the method to return either the translated string, or null
public static String getTranslatedString(Context currentContext, int id) {
final String DEFAULT_AUTHOR_LOCALE = "en-US";
Locale currentLocale = currentContext.getResources().getConfiguration().getLocales().get(0);
Locale authorsLocale = new Locale(DEFAULT_AUTHOR_LOCALE);
final String stringInCurrentLocale = currentContext.getResources().getString(id);
if (authorsLocale.getLanguage().equals(currentLocale.getLanguage())) {
Log.d(TAG, "When running in the author's locale, we are properly translated");
return stringInCurrentLocale;
} else {
Log.d(TAG, "When running in " + currentLocale + " see if we're different from the author's locale");
Configuration configuration = new Configuration(currentContext.getResources().getConfiguration());
configuration.setLocale(authorsLocale);
Context authorsContext = currentContext.createConfigurationContext(configuration);
String authorsOriginalString = authorsContext.getResources().getString(id);
if (authorsOriginalString.equals(stringInCurrentLocale)) {
return null;
} else {
return stringInCurrentLocale;
}
}
}
Basically, we need to hard-code the language in which we authored the code and the original resources. Then we can compare the current string to the one we originally wrote.
Limitations:
I couldn't find a way to gracefully handle the case of en-GB versus en-US. The code above will return "Select color" in en-GB when we would expect null, since it was never translated to "Select colour". We could change the code to compare the exact locale, instead of just the underlying language, but that would be wrong for cases where the US and Great Britain strings are intentionally identical.
Similarly, this is going to give incorrect results for terms that just don't get translated to some languages ("Wi-Fi", "GPS", "iPhone"). Even though they were translated to the same string, the tool will flag them as being untranslated.
This is not a general tool for all situations, but there are certainly times when we might want to use this.
© 2022 - 2024 — McMap. All rights reserved.