Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android setting Nightmode changes resource language

This is an effect that is difficult to describe.

Our Android app supports two languages, however we don't use the system language but let the user set this in the settings. Then, before attaching the BaseContext of the Application we set the locale configuration.

// in Application class
override fun attachBaseContext(base: Context) {
   super.attachBaseContext(LocaleHelper.onAttach(base))
}

// the LocaleHelper
fun onAttach(context: Context): Context {
   return setLocale(context, getPersistedLanguage(context), getPersistedCountry(context))
}

That way the attachBaseContext call gets a context that has the locale set to e.g. "de" instead of "en" - even if the device is in English.

This works great so far and depending on the settings all resources coming from the context are in that language. However, we now added another setting for the night-mode (i.e. giving the user the option to set the "theme" in either "normal" or "dark mode").

For that reason the idea was to set something like this

if (enableDarkMode) {
  AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else {
  AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}

in the onCreate() of the Application (we also tried in the Activity).

However, doing this, suddenly the resources (at least some) are loaded with the device locale. The menu entries are in the device language. However, checking the Locale.getLanguage() gives me the configured language and dynamically called Strings (e.g. context.getString(R.string.xyz)) also show in the correctly configured language.

This leads to the assumption that the menu resources are somewhat (re)loaded (again) but don't respect the set Locale from the JVM.

Does anyone have any idea how to find that bug? What are we missing here? Are the menu resources loaded differently?

like image 371
Tobias Reich Avatar asked Oct 17 '19 10:10

Tobias Reich


People also ask

What is dark mode on Android?

Dark mode changes the background colors of your phone's apps from light to dark to not only reduce eye strain, but also to make your battery last longer.


1 Answers

I just discovered a hacky solution but in case there is anyone having the same problem this might help a bit:

I added to the activity in the manifest

android:configChanges="uiMode"

telling the Application to "handle ui mode changes myself". In that case the resources stay "untouched" but I'm not sure what other implications this change might have.

So please let me know if you have any further hints on what's going wrong when letting the system / app handle the night mode changes itself.

like image 90
Tobias Reich Avatar answered Oct 14 '22 12:10

Tobias Reich