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

4

我有一个存储在本地变量中的计算字符串。 我无法提前知道该字符串,但我可以确定最终它将是其中一个字符串,其不同语言的翻译在string.xml文件中。

如何将这样一个动态字符串翻译为当前语言环境?


1
对于动态翻译,请勿将字符串放入string.xml文件中,该文件仅用于静态资源。请使用编程方式来实现。 - AndRSoid
1个回答

4
尽管这样会花费很长时间,但您可以遍历所有字符串,检查它们是否匹配,并在匹配时返回本地化版本:
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;
}

非常有用!一个注意点:现在设置 config.locale 已经被弃用了。请使用 config.setLocale(Locale); - spartygw
另外,Resources构造函数已被弃用,您不再需要使用AssetsDisplayMetrics。请使用Context::createConfigurationContext - spartygw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接