【发布时间】:2011-07-11 15:01:01
【问题描述】:
我可以根据例如更改应用程序语言运行时吗?通过使用 Android 本地化支持在菜单中选择用户(不是一些自己的/第 3 方解决方案)?
非常感谢
【问题讨论】:
标签: android localization
我可以根据例如更改应用程序语言运行时吗?通过使用 Android 本地化支持在菜单中选择用户(不是一些自己的/第 3 方解决方案)?
非常感谢
【问题讨论】:
标签: android localization
我在应用中实现了按按钮时的语言切换。这在 Android 中并不简单,但可以做到。有两个主要问题: 1) 更改区域设置不会更改系统配置 - 系统区域设置。例如在您的应用程序中将语言更改为法语并不会改变您的设备设置为例如英语的事实。因此,在您的应用程序中的任何其他配置更改 - 方向、键盘隐藏等时,应用程序的区域设置会返回到系统区域设置。 2) 另一个问题是在您的应用程序中更改语言环境不会刷新 UI,也不会重绘视图。这使得在运行时切换变得困难。刷新/重新加载必须手动完成,这意味着必须有一种方法使用本地化的文本/消息/值刷新每个视图。
所以,首先您需要定义本地化资源:value、value-en、value-fr 等。然后这将是例如按下按钮的代码。
private Locale myLocale;
private void onFR_langClicked(View v){
myLocale = new Locale("fr");
// set the new locale
Locale.setDefault(myLocale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
// refresh UI - get values from localized resources
((RadioButton) findViewById(R.id.butn1)).setText(R.string.butn1);
((RadioButton) findViewById(R.id.butn2)).setText(R.string.butn2);
spin.setPromptId(R.string.line_spinner_prompt);
...
}
最好将这两个步骤用两种方法分开:一种是切换调用 UI 刷新的语言环境。
然后您还需要处理配置更改,并确保语言符合您的预期。 Google 建议不要自己处理配置更改。清单必须为每个活动包含这个:
<activity
android:name=". ..."
android:configChanges="locale|orientation|keyboardHidden" >
它允许您定义自己的更改处理程序:
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
if (myLocale != null){
newConfig.locale = myLocale;
Locale.setDefault(myLocale);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
}
}
希望这会有所帮助。希望你明白其中的原理。
【讨论】: