androidkotlindependency-injectionkoinonconfigurationchanged

Koin Update Android Context After Configuration Changed


I'm working on an application that supports multiple languages so when users change the language we start splash activity with Intent.FLAG_ACTIVITY_CLEAR_TOP, FLAG_ACTIVITY_CLEAR_TASK, and FLAG_ACTIVITY_NEW_TASK flags then finish the language activity.

Intent mIntent = new Intent(this, SplashActivity.class);
    mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(mIntent);
    finish();

We have created wrapper class to wrape the application resources

class AppResources(private val context: Context): IAppResources {

    override fun getString(resId: Int): String {
        Logger.i("Current locale language is: ${context.resources.configuration.locale.language}")
        return context.getString(resId)
    }

    override fun getStringArray(resId: Int): Array<String> {
        Logger.i("Current locale language is: ${context.resources.configuration.locale.language}")
        return context.resources.getStringArray(resId)
    }

}

Then we inject this class using Koin like this

factory<IAppResources> {
        Logger.i("Current androidContext language is: ${androidContext().resources.configuration.locale.language}")
        AppResources(androidContext())
    }

The issue is that when we get string value from resources we got it with wrong localization as the Koin already started with previouse android context and AppResources class already inialized with old context. So any suggestion to solve this issue.


Solution

  • The androidContext() in koin is usually an Application Context.

    I believe the configuration overriding code you have for your multi-language support is only applied to Activity.

    You need to wrap the application context with your Configuration overrides inside the factory. E.g. something like

    factory<IAppResources> {
        val original = androidContext()
        val config = Configuration().apply {
            setTo(original.resources.configuration)
            setLocale(yourLocale)
        }
        return@factory AppResources(original.createConfigurationContext(config))
    }