1

I am trying to change the app language programmatically when language name is clicked on in the navigation drawer list. The language changes but I am not able to maintain when the app is closed. here my setLocal method

private void setLocale(String lang) {
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
    getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());

        SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE).edit();
        editor.putString(MY_LANG,lang);
        editor.apply();
    }

I call this method when I want to change the lang like this

              if (id == R.id.ar_lang){
                    setLocale("ar");
                    recreate();
                }
                if (id == R.id.eng_lang){
                    setLocale("en");
                    recreate();
                }

and I call this method in onCreate to get the stored language, but it doesn't work.

public void loadLocale(){
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
        String languages =  prefs.getString(MY_LANG,"");
        setLocale(languages);
    }
ROJ
  • 57
  • 7

2 Answers2

1

I am using https://stackoverflow.com/a/34675427/519334 to change app language at runtime.

and I call this method in onCreate to get the stored language, but it doesn't work.

my solution ony works if languagesetup is done (loadLocale()) before super.OnCreate() is called

@Override
protected void onCreate(Bundle savedInstanceState) {
    loadLocale();
    super.onCreate(savedInstanceState);
    ... initialize
}
k3b
  • 14,517
  • 7
  • 53
  • 85
0

You should just pass context with new configuration to your activity

Use this LocaleHelper (written in Kotlin, but you do it by yourself in Java also)

Then in your activity call this method

override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(LocaleHelper.onAttach(newBase!!))
}

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) 
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP 
          && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
        // update overrideConfiguration with your locale
        overrideConfiguration?.setLocale(LocaleHelper.getCurrentLocale(this))
        overrideConfiguration?.setLayoutDirection(LocaleHelper.getCurrentLocale(this))
    }
    super.applyOverrideConfiguration(overrideConfiguration)
}
Rasul
  • 727
  • 7
  • 20