4

I want user to select a language inside the app. Once the language is selected, I want the strings to use the particular language.

If I change the phone language, then my app runs on the set language.

I am not able to find any way to set a language without changing the phone language. In addition, the changes should be reflected once the language is set.

Could anyone please suggest a way to do it?

Sujit Devkar
  • 1,195
  • 3
  • 12
  • 22

1 Answers1

8

Try this

public static void changeLang(Context context, String lang) {
    Locale myLocale = new Locale(lang);
    Locale.setDefault(myLocale);
    android.content.res.Configuration config = new android.content.res.Configuration();
    config.locale = myLocale;
    context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}

Lang parameter should be "en" for English, "it" for Italian... After that you should restart your activity/fragment

aloj
  • 3,194
  • 7
  • 27
  • 38
  • 1
    What's the best way to restart the activity? And how can I implement this into settings? – A P Jan 17 '17 at 10:18
  • @Avi, just simply called `recreate()` in Activity after changing the language. – Sam Jul 21 '17 at 09:19
  • Without recreating activity or fragment is it possible?@aloj, @Sam – Maulik Dodia Jun 25 '18 at 09:05
  • @MaulikDodia yes, it is possible. aloj code does work! – Sam Jun 26 '18 at 09:50
  • @Sam I tried aloj's code but it doesn't work without **recreating / refreshing** activity. – Maulik Dodia Jun 26 '18 at 09:54
  • @MaulikDodia It is really hard to help without the sample code of what you have done (especially your logic). But I can tell you, aloj answer above does work. I am also quite **new** with Android. Perhaps aloj can help? – Sam Jun 27 '18 at 06:30
  • @Sam My StackOverflow question is [here](https://stackoverflow.com/questions/51020167/changing-the-app-language-run-time-without-recreating-the-activity). If you get time kindly look into it. – Maulik Dodia Jun 27 '18 at 08:48
  • 1
    The solution just work in the current activity, if you back to the previous activity it doesn't work any more. – zeleven Aug 27 '18 at 12:33
  • @Sam "just simply called recreate() in Activity after changing the language" and how do you know this when the user goes to their settings and changes language? Not just something happens within the controlled environment of your app? – portfoliobuilder Sep 20 '18 at 01:30