android - 如何更改片段的语言运行时
问题描述
我正在使用navigation component
单活动架构。我正在尝试在运行时更改我的应用程序的语言,我正在使用这篇文章来这样做。
所以我有以下文件:
运行时LocaleChanger
object RuntimeLocaleChanger {
fun wrapContext(context: Context): Context {
val savedLocale = Locale(PreferencesHelper.readLanguageCode()) // load the user language from SharedPreferences
// as part of creating a new context that contains the new locale we also need to override the default locale.
Locale.setDefault(savedLocale)
// create new configuration with the saved locale
val newConfig = Configuration()
newConfig.setLocale(savedLocale)
return context.createConfigurationContext(newConfig)
}
fun overrideLocale(context: Context) {
val savedLocale = Locale(PreferencesHelper.readLanguageCode()) // load the user language from SharedPreferences
// as part of creating a new context that contains the new locale we also need to override the default locale.
Locale.setDefault(savedLocale)
// create new configuration with the saved locale
val newConfig = Configuration()
newConfig.setLocale(savedLocale)
// override the locale on the given context (Activity, Fragment, etc...)
context.createConfigurationContext(newConfig)
// override the locale on the application context
if (context != context.applicationContext) {
context.applicationContext.run { createConfigurationContext(newConfig) }
}
}
}
应用
override fun attachBaseContext(base: Context) {
super.attachBaseContext(RuntimeLocaleChanger.wrapContext(base))
}
主要活动
override fun attachBaseContext(base: Context) {
super.attachBaseContext(RuntimeLocaleChanger.wrapContext(base))
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
RuntimeLocaleChanger.overrideLocale(this)
}
我改变这样的语言:
// PreferencesHelper.readLanguageCode() is the language code saved in SharedPreferences
if(PreferencesHelper.readLanguageCode() == "en") {
PreferencesHelper.writeLanguageCode("he")
} else {
PreferencesHelper.writeLanguageCode("en")
}
我觉得有什么东西不见了,但我无法理解它
解决方案
我找到了一个解决方案:
主要活动:
override fun onAttachedToWindow() {
super.onAttachedToWindow()
// Will give the direction of the layout depending of the Locale you've just set
window.decorView.layoutDirection = Locale.getDefault().layoutDirection
}
分段
// PreferencesHelper.readLanguageCode() is the language code saved in SharedPreferences
if(PreferencesHelper.readLanguageCode() == "en") {
PreferencesHelper.writeLanguageCode("he")
} else {
PreferencesHelper.writeLanguageCode("en")
}
(activity as? MainActivity)?.recreate()
我还找到了一个不错的图书馆locale-helper
推荐阅读
- list - SwiftUI:围绕 UITableView 实现包装器以实现自定义 List-like 视图
- python - 根据每个唯一 ID 的最新时间过滤数据帧,将所有其他数据保留在数据帧中
- vuejs2 - VueJS 的 Select2 中的多选。有时返回空白选中
- python - 拼接字符串以获取第一个空格左侧和右侧空格右侧的所有内容
- c - 'ptr = &array[index]' 和 '*ptr = array[index]' 有什么区别?
- button - 1Hz计数速度下十进制计数器项目的去抖代码校正
- python-3.x - 限制字符数
- html - 基于父高度的 CSS Square
- docker - docker构建上下文和敏感数据
- flutter - Flutter/Dart:等效于整数的“子字符串”