Possible Duplicate:
Change language programatically in Android
can I change the application language runtime based on e.g. user selection in menu by using the Android localization support (not some own/3rd party solution)?
Thanks a lot
Possible Duplicate:
Change language programatically in Android
can I change the application language runtime based on e.g. user selection in menu by using the Android localization support (not some own/3rd party solution)?
Thanks a lot
I implemented language switch on button press in an app. It's not straight forward in Android, but it can be done. There are two main problems: 1) Changing locale doesn't change System configuration - System locale. Changing the language to French for example in your app, doesn't change the fact that your device is set up for example in English. So at any other config change in your app - orientation, keyboard hiding etc, app's locale goes back to system locale. 2) The other problem is that changing locale in your app doesn't refresh the UI, it doesn't redraw the views. That makes it hard to switch in runtime. The refresh/reload has to be done manually, meaning there has to be a method refreshing every view with localized text/message/value.
So, first you need to define localized resources: value, value-en, value-fr etc. Then this would be the code to make the switch on button press for example.
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);
...
}
It would be good practice to separate the two steps in two methods: one to switch locale which calls the UI refresh.
Then you also need to handle the config change, and make sure the language stays what you intended. Google advises against handling config change yourself. Manifest has to contain this for every activity:
<activity
android:name=". ..."
android:configChanges="locale|orientation|keyboardHidden" >
which allows you to define your own change handler:
@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());
}
}
Hope this helps. Hope you understand the principle.