The Locale does work when have many modules.
Context:
We use Crowdin (this lib apply a wrapper above context)
The app works perfectly when only is a single module
Use Appcompat:1.2
When Change the locale works
but, when i add a new module in app the change locale does work. implementation project(":newmodule")
When is Single Module:
BaseContext=CrowdinContextWrapper
When is Multi Module:
BaseContext=ContextThemeWrapper
Activity extended BaseActivity
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
Crowdin.forceUpdate(context = this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
open class BaseActivity : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(Crowdin.wrapContext(Localization.wrap(context = newBase)))
}
}
class Localization(base: Context) : ContextThemeWrapper(base, R.style.AppTheme) {
companion object {
fun wrap(context: Context, language: String = "es", country: String = "MX"): ContextThemeWrapper {
var ctx = context
val config = context.resources.configuration
if (language != "") {
val locale = Locale(language, country)
Locale.setDefault(locale)
config.setLocale(locale)
// Used setLayoutDirection for RTL and LTR
config.setLayoutDirection(locale)
ctx = context.createConfigurationContext(config)
}
return Localization(ctx)
}
}
}
Explanation
The problem is related to
Appcompat. There are two different fixes depending on the version ofAppCompat. Since you are using1.2.0, you will have to implement that one.AppCompatDelegateImplends up removing the locale, because essentially a ContextThemeWrapper wraps your ContextWrapper. See the implementation @ AppCompatDelegateImpl.java line 368 . Also lines 388, and 480.The work-around for this is to over-ride
getDelegateinside your Base Activity like this:And you also need the following class ( see : Change Locale not work after migrate to Androidx ).
References
https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/appcompat/appcompat/src/main/java/androidx/appcompat/app/AppCompatDelegateImpl.java#368
Change Locale not work after migrate to Androidx
https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/appcompat/appcompat/src/main/java/androidx/appcompat/app/AppCompatDelegateImpl.java#368