3 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
您需要將新的配置上下文傳遞給 ContextWrapper 超類。
在您的活動(dòng)中覆蓋 attachBaseContext 并將新上下文傳遞為 -
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(updatedConfigurationContext(base));
}
并從 getApplicationContext().createConfigurationContext(configuration);
正如你在上面所做的那樣。

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
不知道你想在哪里做這個(gè),所以我只是假設(shè)它在一個(gè)活動(dòng)中。這個(gè)答案也在 Kotlin 中,如果你想在 Java 中使用它,請(qǐng)檢查以下帖子: How to convert a kotlin source file to a java source file
活動(dòng):
override fun attachBaseContext(ctx: Context?) {
super.attachBaseContext(ContextWrapper.wrap(ctx, yourLocale))
}
上下文包裝器:
class ContextWrapper(context: Context?) : android.content.ContextWrapper(context) {
companion object {
fun wrap(context: Context?, locale: Locale): ContextWrapper {
val configuration = context?.resources?.configuration
configuration?.setLocale(locale)
if (Build.VERSION.SDK_INT >= 24) {
val localeList = LocaleList(locale)
LocaleList.setDefault(localeList)
configuration?.locales = localeList
}
val ctx = if(configuration != null) context.createConfigurationContext(configuration) else null
return ContextWrapper(ctx)
}
}
}
重新創(chuàng)建您的上下文(活動(dòng)):
recreate()在您的活動(dòng)中使用以重新啟動(dòng)您的活動(dòng)上下文。

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可能需要在更改默認(rèn)語言環(huán)境后重新創(chuàng)建活動(dòng)。
getActivity().recreate();
添加回答
舉報(bào)