I'm working on an app that allows you to change the language locally.
To make this work without having to restart the app, I'm using the ContextWrapper on the BaseActivity, where I assign the language to the context:
override fun attachBaseContext(newBase: Context{
super.attachBaseContext(ContextWrapper(newBase.setAppLocale(Session.getLanguage())))
}
To change the language, I have used both the setLocale legacy and the ApplicationDelegate:
Legacy
fun setLocale(lang: String) {
val myLocale = Locale(lang.toString())
Locale.setDefault(myLocale)
val res = resources
val dm = res.displayMetrics
val conf = res.configuration
conf.locale = myLocale
res.updateConfiguration(conf, dm)
}
New API SDK 33
val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags(it)
AppCompatDelegate.setApplicationLocales(appLocale)
They both do pretty much the same thing. The 2nd is more efficient since it recreates the layouts itself.
The problem is that I am using an architecture with ViewModels that implement a RESOURCES Wrapper to get certain types of resources inside the ViewModel without having leaked a context. There is no mistake on the part of the team in using something wrong.
The wrapper is as follows:
class ResourceManager(val context: Context) {
fun getColor(@ColorRes resId: Int): Int = ContextCompat.getColor(getContextWrapped(), resId)
fun getString(@StringRes resId: Int): String = getContextWrapped().getString(resId)
fun getDrawable(@DrawableRes resId: Int): Drawable? = getContextWrapped().getDrawable(resId)
private fun getContextWrapped(): Context {
return ContextWrapper(context.setAppLocale(Session.getLanguage()))
}
}
What is the real problem? The problem is that this ResourceManager uses a CONTEXT that when changing the language, this CONTEXT remains with the previous LANGUAGE resource. That is, if the app starts in English and I change it to Italian, the ResourceManager will stay in English.
The solution I found is to Restart HILT as I did with Dagger before, which generated a new component and cleaned the old one. But, with HILT, I don't know how this can be achieved. How can I override singleton resources and create new ones.