Вопрос

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?

Нет правильного решения

Другие советы

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;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top