【发布时间】:2015-03-05 13:54:06
【问题描述】:
我怎样才能以不同于用户当前语言环境的语言访问字符串资源。
String string = context.getString(R.string.string_id, "en");
【问题讨论】:
标签: java android android-resources
我怎样才能以不同于用户当前语言环境的语言访问字符串资源。
String string = context.getString(R.string.string_id, "en");
【问题讨论】:
标签: java android android-resources
您可以设置应用配置。使用这个:
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, null);
然后你可以使用:
String string = context.getResources().getString(R.string.string_id);
祝你好运。
【讨论】:
您通常会在加载 Activity 的布局之前修改语言。 此外,您必须在 res 中创建“value”的“value-en”克隆文件夹。在此文件夹中,您必须将相同的字符串和资源、名称相同但翻译成另一种语言。当您将这些克隆文件夹创建到“res”文件夹中时,您可以在确定活动的语言后以经典方式调用资源。它看起来像这样:
try{
Configuration c = new Configuration(getResources().getConfiguration());
String lingua = readFileAsString("/sdcard/Lingua.txt");
if(lingua.equals("")){
c.locale = Locale.ITALIAN;
}else if(lingua.equals("ITALIANO")){
c.locale = Locale.ITALIAN;
}else if(lingua.equals("ENGLISH")){
c.locale = Locale.US;
}
getResources().updateConfiguration(c, getResources().getDisplayMetrics());
}catch(Exception e){ }
setContentView(R.layout.main);
opzioni[0] = getResources().getString(R.string.home);
opzioni[1] = getResources().getString(R.string.indietro);
opzioni[2] = getResources().getString(R.string.disattiva_audio);
opzioni[3] = getResources().getString(R.string.chiudi);
opzioni[4] = getResources().getString(R.string.ripeti);
在此示例中,我将文本文件中的语言恢复到 sdcard 中,并且在对布局进行充电之前,我设置了语言。如您所见,getResources() 没有指定语言...但它会转到带有解释正确语言后缀的文件夹克隆。
【讨论】: