我有一个单一的活动应用程序,语言设置大多按预期工作。onCreateView()
我通过文本的资源 ID设置每个视图的文本。但有时,当我进入我的应用程序时,语言是系统默认的,而不是选择的语言。当我从深层链接(小部件或通知)导航到应用程序时也会发生同样的情况。当我导航到另一个片段并返回时,一切都会在正确的区域设置下变得正确。
我试图调试我的应用程序以发现原因。我根据系统默认值获得的每个资源 ID 文本,而不是选择的语言。当我包装我的片段上下文然后获取文本时,我得到了正确的结果。
这就是我设置语言的方式:
private fun changeLang(lang: String, country: String) {
activity?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResources(it, lang, country)
}
updateResourcesLegacy(it, lang, country)
}
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String, country: String) {
val locale = Locale(language, country)
Locale.setDefault(locale)
val resources: Resources = context.resources
val configuration: Configuration = resources.configuration
configuration.setLocale(locale)
context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String, country: String) {
val locale = Locale(language, country)
Locale.setDefault(locale)
val resources: Resources = context.resources
val configuration: Configuration = resources.configuration
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
}
在我的活动中,我覆盖了以下方法:
override fun attachBaseContext(newBase: Context?) {
newBase?.let {
val pref = Preference(PreferenceHelper.customPrefs(it))
super.attachBaseContext(ContextWrapper.wrap(newBase, pref.language, pref.country))
}
}
class ContextWrapper(base: Context?) : android.content.ContextWrapper(base) {
companion object {
fun wrap(context: Context?, lang: String? = "uz", country: String? = ""): ContextWrapper =
wrap(context, Locale(lang, country))
fun wrap(context: Context?, newLocale: Locale): ContextWrapper {
var localizedContext = context
val res = localizedContext?.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?.setLocales(localeList)
localizedContext = localizedContext?.createConfigurationContext(configuration!!)
}
else -> {
configuration?.setLocale(newLocale)
localizedContext = localizedContext?.createConfigurationContext(configuration!!)
}
}
res?.updateConfiguration(configuration, res.displayMetrics)
return ContextWrapper(localizedContext)
}
}
}