I have a multi-language app whose Locale
is changed programmatically.
When the application is first created, it looks into a specific SharedPreferences
file and set the locale accordingly.
Then the user can go into a specific Activity P
and choose among the available languages (now only two languages are available).
This is what I do in P
, with lang
being a 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();
The activity MainActivity
receives a new Intent
and does this:
@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
In this way, MainActivity
's onCreate is called again and the resources loaded again in the new Locale
.
Everything is ok, but one thing.
All the strings appear in the correct locale, but the titles of all the activities stay in the language they were first created when the app was launched. They did not change. My activities are actually instances of ActionBarActivity
and the titles are shown in SupportActionBar
.
Question: how can I force those titles to be changed according to the current Locale
?
Note: A simple solution is to call getSupportActionBar().setTitle(getString(R.string.title_activity_X));
for every Activity X
. However, since there are quite a few activities I would rather find a way to have it done automagically.
Note: I am using API Level 19, with support library v7.