Search code examples
androidlocale

Change locale immediately


i want my app locale to be changeable in app. So i use this code in order to do that:

            String languageToLoad  = "fa";
            Locale locale = new Locale(languageToLoad);
            Locale.setDefault(locale);
            Configuration config = new Configuration();
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, null);

but the thing is that i will see the changes after closing and opening my app manually. But i want it to occur immediately in the app after that lines of code.

i have tried by transferring my code to onStart() instead of onCreate() method and calling onRestart() after that lines of code. But it didn't work.

What should i do in order to achieve that


Solution

  • Use this piece of code..

    public void setLocale(String lang) {
            myLocale = new Locale(lang);
            Resources res = getResources();
            DisplayMetrics dm = res.getDisplayMetrics();
            Configuration conf = res.getConfiguration();
            conf.locale = myLocale;
            res.updateConfiguration(conf, dm);
    
            Intent refresh = new Intent(this, YourActivity.class);
            startActivity(refresh);
            finish();
        }