I added day/night mode option in my android app as explained here. But when I change it, the language changes automatically.
This is my function
public void enableDarkMode(boolean enable){
Log.d(""+ this.TAG, "Dark Mode = "+enable);
this.editorDarkMode.putBoolean(IS_DARK_MODE_ON, enable);
this.editorDarkMode.commit();
if (enable){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
I searched a lot but didn't achieve any solution yet.
Edit1: this is how I store the lang.
public void setLanguage(String lang){
this.editorLang.putString("Language", ""+lang);
this.editorLang.commit();
Locale locale = new Locale(""+ lang);
Locale.setDefault(locale);
Configuration configuration = new Configuration();
configuration.locale = locale;
this.context.getResources().updateConfiguration(configuration,this.context.getResources().getDisplayMetrics());
}
The problem that when you change the dark mode, the activity restarts with the default settings (default language), so you need to explicitly force the user's language.
But setting that explicitly every time you change the dark mode could be boilerplate, and this also could require a one more restart of the activity to apply the language.
Instead of that, you can use a customized
ContextWrapperwhere you can apply the preferred language at the very beginning of your app in theattachBaseContext()activity callback by wrapping this customizedContextWrapper:The custom context wrapper:
Override
attachBaseContext()in the activity: