Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Arabic Language Support Problem in Some Devices

I'm trying to support the Arabic language. When I changed the language in the application with the following code (refer below), in most of the devices it works fine but in some devices such as Galaxy S7, Galaxy S8, LG G5 UI transforms to RTL successfully but Arabic language resources are not being loaded and the app still uses EN string resources.

Has anyone had any opinions about this problem? Thanks for answers.

Here is the code I use for changing language:

 private fun updateResources(context: Context, locale: Locale): Context {
        Locale.setDefault(locale)
        val res = context.resources
        val config = res.configuration
        config.setLocale(locale)
        config.setLayoutDirection(locale)
        BaseActivity.setLayoutDirection(res.configuration.layoutDirection)
        Session.lang = locale.language

        return context.createConfigurationContext(config)
    }
like image 875
savepopulation Avatar asked Nov 06 '22 07:11

savepopulation


1 Answers

In your activity, override attachBaseContext function

override fun attachBaseContext(base: Context) {
    super.attachBaseContext(updateBaseContextLocale(base))
}

updateBaseContextLocale function is like below;

private fun updateBaseContextLocale(context: Context): Context {
    val languageCode = LanguageUtils.getLanguageCode(LocalSharedPrefs.getLanguage(context))
    return AppUtils.updateLocale(context, languageCode)
}

In AppUtils updateLocale function is like that;

@JvmStatic
fun updateLocale(context: Context, languageCode: String): Context {
    val locale = Locale(languageCode)
    Locale.setDefault(locale)

    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        updateResourcesLocale(context, locale)
    } else {
        updateResourcesLocaleLegacy(context, locale)
    }
}

private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
    val resources = context.resources
    val configuration = resources.configuration
    configuration.locale = locale
    configuration.setLayoutDirection(locale)
    resources.updateConfiguration(configuration, resources.displayMetrics)
    return context
}

@TargetApi(Build.VERSION_CODES.N)
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
    val configuration = context.resources.configuration
    configuration.setLocale(locale)
    configuration.setLayoutDirection(locale)
    return context.createConfigurationContext(configuration)
}

I hope your problem can be solved with that answer :)

like image 95
Halil ÖZCAN Avatar answered Nov 11 '22 11:11

Halil ÖZCAN