I am working on an Android app which needs to be bilingual (English/Spanish). I allow the user to select the desired language from a Preference and perform the following locale change in the app’s main activity (a subclass of TabActivity) based on the selected language:
private void setApplicationLanguage(String languageCode)
{
// Set the locale to the specified language code.
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale(languageCode.toLowerCase());
res.updateConfiguration(conf, dm);
}
The main activity hosts four tabs, each with its own Activity (sometimes ActivityGroup). What I would like to have happen is when the language changes, all open activities are simply restarted which causes their strings to be reloaded in the appropriate language. Also acceptable (but less desirable) would be total destruction of all the open activities, requiring the user to start the app again manually and thus all the strings would be reloaded in the appropriate language.
I have tried calling finish() from the main activity which causes that activity to quit. However, when I restart the app, the child activities “hosted” by the main activity (one for each tab) still appear in the prior language. I assume this is because the child activities weren’t recursively “finished” for me.
I have also tried including/excluding the “locale” attribute from AndroidManifest.xml on the main activity as well as other activities, but I never see an activity restart upon a change in local. Then again, how would the “restart” manifest itself? Would it call onCreate() or simply onResume(), or even something else? If this approach would automagically restart the activities, calling onCreate() when the locale changes, then it sounds like specific guidance on how to make this happen would be the best route in my case.
The solution needs to run on Android API level 7, so creating a new Intent with the flag FLAG_ACTIVITY_CLEAR_TASK apparently is not available option.
You can use a
BroadcastReceiveras an inner class of eachActivityused for the tab content.Register the receiver in
onResumeand un-register it inonPause.Have the main
Activitysend a ‘sticky’ broadcast when the locale is changed and use the result ofregisterReceiverinonResumeto retrieve theIntentto see whether the locale has changed. This should also work for any ‘visible’Activityto allow it to dynamically update the data.