【发布时间】:2015-04-25 15:49:52
【问题描述】:
我有一个多语言应用程序,其 Locale 以编程方式更改。
首次创建应用程序时,它会查看特定的SharedPreferences 文件并相应地设置区域设置。
然后用户可以进入特定的Activity P 并在可用语言中进行选择(现在只有两种语言可用)。
这就是我在 P 中所做的,lang 是 String:
// set locale to that chosen by the user
((MyApp) getApplication()).setMyAppLocale(lang);
// get the Locale object
Locale locale = ((MyApp) getApplication()).getMyAppLocale();
// classic code
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
// clear the activity stack and restart the MainActivity
Intent intent = new Intent(this, MainActivity.class);
Bundle extras = new Bundle();
extras.putBoolean(MainActivity.PARAM_DO_RESTART, true);
intent.putExtras(extras);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
活动MainActivity 接收新的Intent 并执行以下操作:
@Override
public void onNewIntent(Intent anotherIntent) {
super.onNewIntent(anotherIntent);
setIntent(anotherIntent);
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(extras != null) {
if (extras.getBoolean(PARAM_DO_RESTART, false)) {
intent.putExtra(PARAM_DO_RESTART, false);
setIntent(intent);
finish();
startActivity(intent);
}
} // if extras != null
这样,MainActivity 的 onCreate 被再次调用,资源再次加载到新的Locale 中。
一切都很好,只有一件事。
所有字符串都显示在正确的语言环境中,但所有活动的标题仍使用它们最初创建的语言,当应用程序启动时。他们没有改变。我的活动实际上是ActionBarActivity 的实例,标题显示在SupportActionBar 中。
问题:如何强制根据当前的Locale更改这些标题?
注意:一个简单的解决方案是为每个Activity X 调用getSupportActionBar().setTitle(getString(R.string.title_activity_X));。但是,由于有很多活动,我宁愿找到一种自动完成的方法。
注意:我使用的是 API 级别 19,支持库 v7。
【问题讨论】:
标签: android locale android-support-library