[英]android: programmatically localize a dynamic string
我有一個存儲在局部變量中的計算字符串。 我無法事先知道字符串,但是我確定最終它將是字符串之一,其翻譯為不同的語言在 string.xml 文件中。
如何將這樣的動態字符串轉換為當前語言環境?
雖然這需要很長時間,但您可以遍歷所有字符串,檢查它們是否匹配,如果匹配則返回本地化版本:
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.