1

The following code is working on API > 26 but not on API 25 and below , I've checked this solution on SO Android N change language programmatically but it's not working for me , I've also found that this issue may be caused by AppCompat implementation of AndroidX v1.0.0 as described here createConfigurationContext not working on API level <26 to change language programmatically but already I am using the version 1.2.0

Here is my code :

1- Class ContextUtils.kt

 @Suppress("DEPRECATION")
    class ContextUtils(base: Context) : ContextWrapper(base) {
    
        companion object {
    
            fun updateLocale(c: Context, localeToSwitchTo: Locale): ContextWrapper {
                var context = c
                val resources: Resources = context.resources
                val configuration: Configuration = resources.configuration
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    val localeList = LocaleList(localeToSwitchTo)
                    LocaleList.setDefault(localeList)
                    configuration.setLocales(localeList)
                } else {
                    configuration.locale = localeToSwitchTo
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
                    context = context.createConfigurationContext(configuration)
                } else {
                    resources.updateConfiguration(configuration, resources.displayMetrics)
                }
                return ContextUtils(context)
            }
        }
    }

2- Class BaseActivity.kt

   open class BaseActivity: AppCompatActivity() {
    
        override fun attachBaseContext(newBase: Context) {
            val localeToSwitchTo = Pref(newBase).getPrefString("lang")    // get language from preference

            val localeUpdatedContext: ContextWrapper = ContextUtils.updateLocale(newBase, Locale(localeToSwitchTo))
            super.attachBaseContext(localeUpdatedContext)
        }
    
    }

3- MainActivity

class MainActivity :BaseActivity() {
       override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    }
  override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(newBase)
    }
}

PS : If I change the language manually on the device (API < 25) and run the app again , the language on the app will change also.

Thanks!

anehme
  • 536
  • 1
  • 6
  • 18

0 Answers0