解决Android多语言失效问题
本文最后更新于 433 天前,其中的信息可能已经有所发展或是发生改变。

今天写项目的时候发现切换指定语言之后,可能会部分失效,在搜索引擎逛了一圈,基本上都是用了attachBaseContext(Context newBase)这个方法,在查阅更多资料之后,才发现这个方法才是罪魁祸首。

在androidx中,Activity都是继承AppCompatActivity,而顺着getResource().getString()方法,最终找到了Context.ContextWrapper.ContextThemeWrapper。

AppCompatActivity.class

这个super.getResources()就来自ContextThemeWrapper。

实际上,在androidx中,决定语言的不再是attachBaseContext中的newBase,而是这个ContextThemeWrapper,所以我们只需要将语言配置应用到这个上面即可。

@Override
protected void attachBaseContext(Context newBase) {
    // Language
    langId = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(newBase).getString("language","0"));
    _Language = Languages.getLanguageById(langId);
    Resources resources = newBase.getResources();
    Configuration configuration = resources.getConfiguration();

    // 将此处换成你的语言判断逻辑
    Locale locale = Locale.getDefault();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        configuration.setLocales(localeList);
    } else {
        configuration.setLocale(locale);
    }
    Context targetContext = newBase.createConfigurationContext(configuration);

    // 将R.style.Theme改成你自己的主题id
    final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(targetContext, R.style.Theme) {
        @Override
        public void applyOverrideConfiguration(Configuration overrideConfiguration) {
            if (overrideConfiguration != null) {
                overrideConfiguration.setTo(configuration);
            }
            super.applyOverrideConfiguration(overrideConfiguration);
        }
    };
    super.attachBaseContext(wrappedContext);
}
未经允许禁止转载本站内容,经允许转载后请严格遵守CC-BY-NC-ND知识共享协议4.0,代码部分则采用GPL v3.0协议
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇