【发布时间】:2021-06-23 18:36:05
【问题描述】:
对于我们想要使用应用通过 Play 核心库下载的语言资源的每个活动,我们需要更新基本上下文并通过其配置设置新的语言环境:
override fun attachBaseContext(base: Context) {
val configuration = Configuration()
configuration.setLocale(Locale.forLanguageTag(sharedPrefs.getString(LANGUAGE_SELECTION)))
val context = base.createConfigurationContext(configuration)
super.attachBaseContext(context)
SplitCompat.install(this)
}
如您所见,语言是从共享首选项中检索的。然而,使用 MVVM,其中 repository 模式负责处理 Shared Preferences 并且 ViewModel 与它,如何从attachBaseContext() 访问那个ViewModel?
尝试从 attachBaseContext() 调用 ViewModel 会返回以下错误:You can’t request ViewModel before onCreate call。
【问题讨论】:
标签: android mvvm sharedpreferences viewmodel google-play-core