简体   繁体   English

android:以编程方式本地化动态字符串

[英]android: programmatically localize a dynamic string

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.我无法事先知道字符串,但是我确定最终它将是字符串之一,其翻译为不同的语言在 string.xml 文件中。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM