问题描述
我的代码在Java上运行良好,并且当我重构为Kotlin时,它不再更改语言环境。
这是在Application类中声明的函数,我通过传递诸如setLanguageByLocale(“ ar”)之类的语言环境字符串来调用此函数 然后我重新开始活动
fun setLanguageByLocale(language: String?) {
val locale = Locale(language)
Locale.setDefault(locale)
val config = myApplication?.resources?.configuration
config?.setLocale(locale)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
config?.setLocales(LocaleList(locale))
}
myApplication?.resources?.updateConfiguration(config,myApplication!!.resources.displayMetrics)
val context: Context ?= myApplication?.createConfigurationContext(config!!)
val sharedPreferences = myApplication!!.getSharedPreferences(Utils.preferences,MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString(Utils.locale,language)
editor.apply()
}
这是我的自定义上下文说唱歌手类
class MyContextwrapper(base: Context?) : Contextwrapper(base) {
companion object {
@JvmStatic
fun wrap(contextB: Context,newLocale: Locale?): Contextwrapper {
var context = contextB
val res = context.resources
val configuration = res.configuration
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
configuration.setLocale(newLocale)
val localeList = LocaleList(newLocale)
LocaleList.setDefault(localeList)
configuration.setLocale(newLocale)
configuration.setLocales( localeList)
configuration.setLayoutDirection(newLocale)
context = context.createConfigurationContext(configuration)
res.updateConfiguration(configuration,res.displayMetrics)
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 -> {
configuration.setLocale(newLocale)
context = context.createConfigurationContext(configuration)
}
else -> {
configuration.setLocale(newLocale)
res.updateConfiguration(configuration,res.displayMetrics)
}
}
return Contextwrapper(context)
}
}
}
在MainActivity中,我重写了两种方法
override fun attachBaseContext(newBase: Context) {
val locale = Utils.getLocale(newBase)
Locale.setDefault(locale)
super.attachBaseContext(MyContextwrapper.wrap(newBase,locale))
}
override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
if (overrideConfiguration != null) {
val uiMode = overrideConfiguration.uiMode
val locale = Utils.getLocale(this)
Locale.setDefault(locale)
overrideConfiguration.setLocale(locale)
overrideConfiguration.setLayoutDirection(locale)
overrideConfiguration.setTo(baseContext.resources.configuration)
overrideConfiguration.uiMode = uiMode
}
super.applyOverrideConfiguration(overrideConfiguration)
}
我有默认设置的strings.xml和用于区域设置的strings.xml
我正在使用implementation 'androidx.appcompat:appcompat:1.2.0'
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)