安卓设置夜间模式会改变资源语言。

10

这是一种难以描述的效果。

我们的安卓应用支持两种语言,但我们不使用系统语言而是让用户在设置中设置。然后,在附加Application的BaseContext之前,我们设置语言环境。

// in Application class
override fun attachBaseContext(base: Context) {
   super.attachBaseContext(LocaleHelper.onAttach(base))
}

// the LocaleHelper
fun onAttach(context: Context): Context {
   return setLocale(context, getPersistedLanguage(context), getPersistedCountry(context))
}

这样,attachBaseContext调用会获得一个语言环境为"de"而不是"en"的上下文——即使设备本身是以英语运行。

到目前为止,这个方法非常有效,而且根据设置,来自该上下文的所有资源都是使用该语言。然而,我们现在添加了另一个设置,用于夜间模式(即让用户选择在“普通”或“黑暗模式”中设置“主题”)。

因此,我们的想法是设置类似于以下内容:

if (enableDarkMode) {
  AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else {
  AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
在应用程序的onCreate()中(我们也尝试了在Activity中)。
然而,这样做,突然间设备语言环境下的资源(至少有一些)被加载。菜单项是以设备语言呈现的。然而,检查Locale.getLanguage()会给我配置的语言,并且动态调用的字符串(例如context.getString(R.string.xyz))也会显示为正确配置的语言。
这导致假设菜单资源有些被(重新)加载,但是不遵守JVM设置的Locale。
有没有人知道如何找到那个bug?我们漏掉了什么?菜单资源是否以不同的方式被加载?
2个回答

3

我刚刚发现了一个不太正式的解决方案,但如果有人遇到同样的问题,这可能会有所帮助:

我在清单文件中向活动添加了以下内容

android:configChanges="uiMode"

告诉应用程序“自己处理ui模式更改”。 在这种情况下,资源保持“不变”,但我不确定这种更改可能会有什么其他影响。 因此,请告诉我是否有任何进一步的提示,以解决让系统/应用程序自行处理夜间模式更改时出现的问题。

2
也许有些晚了,但这可以帮助其他人。
我成功地确保暗黑主题不会改变本地语言。
为此,我有一个片段,通过一个开关启用暗黑主题。
SettingsFragment:
switchPreference.setOnPreferenceChangeListener((preference, isSwitchOn) -> {
            if((boolean) isSwitchOn){
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            }
            return true;
        });

在父活动中,我只需要重写 attachBaseContext 方法!
设置活动:
@Override
    protected void attachBaseContext(Context newBase) {

        // Get configuration and resources before onCreate method
        Resources resources = newBase.getResources();
        Configuration configuration = new Configuration(resources.getConfiguration());
        configuration.uiMode = Configuration.UI_MODE_NIGHT_UNDEFINED;
        Context context = newBase.createConfigurationContext(configuration);

        // Set locale with configuration saved
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String langue = sharedPreferences.getString("langage_pref", "fr");
        Locale locale = new Locale(langue);
        Locale.setDefault(locale);
        configuration.setLocale(locale);
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        super.attachBaseContext(newBase);
    }

希望能帮到你!:D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接