4

I have a computed String stored in local variable. There is no way I can know the string on before hand, however I know for sure in the end it will be one of the Strings whose translations to different languages are inside the string.xml files.

How can I translate such a dynamic string to the current locale?

1
  • 1
    For dynamic translation don't put strings into string.xml. string.xml is only used for static resources. Use programming approach here. Commented Feb 9, 2014 at 9:07

1 Answer 1

4

Although this will take quite long, you could iterate through all the strings, check whether they match, and return the localized version if they do:

public String translatedString(String s)
    //Set the locale to en-us
    Resources standardResources = context.getResources();
    AssetManager assets = standardResources.getAssets();
    DisplayMetrics metrics = standardResources.getDisplayMetrics();
    Configuration config = new Configuration(standardResources.getConfiguration());
    config.locale = Locale.US;
    Resources defaultResources = new Resources(assets, metrics, config);

    //Iterate over string res
    Field fields[] = R.string.class.getFields();
    for (Field field : fields) {
        String value = defaultResources.getString(defaultResources.getIdentifier(field.getName(), "string", this.getPackageName())));
        if (value.equals(s)){
            return getResources().getString(getResources().getIdentifier(field.getName(), "string", this.getPackageName())));
        }

    }

    return null;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Very useful! One note: setting config.locale is depracated now. Use config.setLocale(Locale);
Also, Resourcesconstructor is depracated and you no longer need Assets or DisplayMetrics. Use Context::createConfigurationContext

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.