2

For a mobile application I'm making in Android Studio, I want to make it possible for users to change the language of the application. The idea is as follows: I have multiple strings.xml files (for the different languages) and I want to switch to a specific file when the language is changed (e.g. if language is changed to German, switch to file strings.xml (de)). However, I can't seem to find a way to programmatically switch to another strings.xml file. The only solution I can find online is to change the locale of the system, but I would rather avoid this option. Is there any way to programmatically change the strings.xml file, without changing the locale?

Thanks in advance!

Sytze
  • 23
  • 1
  • 5
  • Possible duplicate of: http://stackoverflow.com/questions/20527164/setting-application-locale-to-pt-br-programmatically – FishStix Jun 27 '16 at 20:39
  • That question is about changing the locale to change the language, which I want to avoid. – Sytze Jun 27 '16 at 20:47
  • 1
    Possible duplicate of [Changing Locale within the app itself](http://stackoverflow.com/questions/2264874/changing-locale-within-the-app-itself) – Sergey Glotov Jun 27 '16 at 21:03
  • That's not about changing system locale, `Locale.setDefault()` changes locale only in the app. – Sergey Glotov Jun 27 '16 at 21:04
  • Just to say it: Your app should not offer this ability. I don't know why exactly you want that feature and you may have a good reason for it, but apps should always use the system language of the phone. That's the language the user selected and therefore he or she wants all the apps to be in that language. – Xaver Kapeller Jul 03 '16 at 15:53

2 Answers2

1

I used the updateConfiguration method thanks to the links of Sergey Glotov like that:

Locale locale2 = new Locale("en");
Locale.setDefault(locale2);

Configuration config2 = new Configuration();
config2.locale = locale2;

getBaseContext().getResources().updateConfiguration(
                        config2,getBaseContext().getResources().getDisplayMetrics());

So now the app is using the string-en resource file! :D

However the Resources.getSystem().getConfiguration().locale.getDisplayLanguage() is "French" so my locale isn't change. Is that what you wanted?

Daniel Alder
  • 5,031
  • 2
  • 45
  • 55
Romain
  • 11
  • 2
0

I would suggest using the Android-LocalizationActivity library.

This library makes it very simple to change the language of your app at runtime. All your activities need to implement the LocalizationActivity, which extends AppCompatActivity. After that you can switch the language used in your app by calling setLanguage("en"); A sample project including the sample code below and more information can be found at the github page.

this question about programmatically changing the language might contain some useful answers as well.

Community
  • 1
  • 1
Rockney
  • 10,380
  • 2
  • 20
  • 26