【问题标题】:Android AppCompatDelegate.setDefaultNightMode not recreating parent activity in android 9Android AppCompatDelegate.setDefaultNightMode 不在 android 9 中重新创建父活动
【发布时间】:2020-02-09 15:58:32
【问题描述】:
您好,我正在使用此 AppCompatDelegate 在日/夜主题之间进行切换
我有 2 项活动 A&B
此代码从活动 B 调用
它应该用所选风格重新创建活动 B & A
这是我的代码
applyNight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isNight) {
SharedPrefrencesMethods.savePreferences(this, getString(R.string.night_key), true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
SharedPrefrencesMethods.savePreferences(this, getString(R.string.night_key), false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
});
我在 android 7 和 6 上对其进行了测试,它工作正常,即在活动 B 中更改模式并按下活动 A 重新创建新主题时。
在 android 9 上尝试它时,它只更改了活动 B 而不会影响它的父活动 A。
【问题讨论】:
标签:
android
android-appcompat
android-night-mode
appcompatdelegate
【解决方案1】:
我也遇到了这个问题,然后在谷歌官方Android开发者博客https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94中听取Chris Banes的建议,首先在应用程序的应用程序类中设置setDefaultNightMode,所以我创建了一个类EcwgApplication扩展Application正如他所展示的,并在清单的application 部分添加了android:name=".EcwgApplication"。我还将用于切换主题的方法也放在应用程序类中,当用户更改主题设置时,我的设置活动可以调用(除了在调用它之前使用更改更新 SharedPreferences),所以它看起来像这样:
public class EcwgApplication extends Application {
public void onCreate() {
super.onCreate();
int selectedDarkLightTheme = PreferenceManager.getDefaultSharedPreferences(this).getInt(getString(R.string.preferences_dark_light_mode_selected_key), AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
AppCompatDelegate.setDefaultNightMode(selectedDarkLightTheme);
}
public static void setDarkLightTheme(int selectedDarkLightTheme) {
AppCompatDelegate.setDefaultNightMode(selectedDarkLightTheme);
}
}
这适用于 Android OS 版本 24 到 29,但使用 21(此应用支持的最低版本)到 23 我会在返回第一个活动时出现黑屏,并且在旋转屏幕时会解决这个问题,它还清楚地表明 UI 状态没有被保存。所以我将设置屏幕的 StartActivity 更改为 StartActivityForResult,并在 onActivityResult 中检查版本号是否this.recreate()。
我需要继续做更多的测试,但至少到目前为止一切似乎都很好。