Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you programmatically switch between xml resource files on android?

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.

like image 547
Chimeara Avatar asked Jul 01 '26 17:07

Chimeara


1 Answers

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.

like image 184
mvds Avatar answered Jul 04 '26 08:07

mvds