configuration.setLocale(locale)与AppCompatDelegate.setDefaultNightMode不兼容

sal*_*tro 4 android setlocale android-10.0 android-dark-theme

如果我将darkmode设置为,AppCompatDelegate.setDefaultNightMode而系统不是黑暗的,则Configuration.setLocale无法使用。我将语言环境更改为,例如,从更改En为It,所有字符串仍然以系统语言显示。

如果我设置了与系统(Android 10)相同的NightMode,则没有问题。android 9或更低版本存在相同的问题:如果我在应用中设置了暗模式,并且更改了上下文语言,则活动会根据系统的语言显示文本。

小智 6

Kotlin解决方案

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
    if (overrideConfiguration != null) {
        val uiMode = overrideConfiguration.uiMode
        overrideConfiguration.setTo(baseContext.resources.configuration)
        overrideConfiguration.uiMode = uiMode
    }
    super.applyOverrideConfiguration(overrideConfiguration)
}
Run Code Online (Sandbox Code Playgroud)

Java解决方案

@Override
public void applyOverrideConfiguration(Configuration overrideConfiguration) {
    if (overrideConfiguration != null) {
        int uiMode = overrideConfiguration.uiMode;
        overrideConfiguration.setTo(getBaseContext().getResources().getConfiguration());
        overrideConfiguration.uiMode = uiMode;
    }
    super.applyOverrideConfiguration(overrideConfiguration);
}
Run Code Online (Sandbox Code Playgroud)