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