3
votes

Android has built in functionality to switch between resources based on a users device language (http://developer.android.com/training/basics/supporting-devices/languages.html), but is it possible to switch the resources manually?

For example if I have: yProject/ res/ values/ strings.xml values-es/ strings.xml values-fr/ strings.xml

Can I change which string file is used based on the users preference rather than their device language? So someone using a french language device can choose to use the English text if they want?

I know I can do it with string variables in my code rather than using the xml, but I feel the xml would be neater.

1

1 Answers

0
votes

Yes you can. This is a copy/paste from a project doing so, based on user preference, to be put in onCreate():

Resources res = getResources();
Configuration conf = res.getConfiguration();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

String def = Locale.getDefault().getDisplayLanguage();
String lang = prefs.getString("LANGUAGE", def);
conf.locale = new Locale(lang);
Log.v("myapp", lang+" = "+conf.locale+" = "+conf.locale.getDisplayName());
res.updateConfiguration(conf, res.getDisplayMetrics());

By setting a user preference named LANGUAGE to the two-letter code of the desired language, and then restarting the Activity, you manually override set the language. By removing the preference you get the system default.