문제

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