Android AppCompatDelegate.setDefaultNightMode未在Android 9中重新创建父活动
您好,我正在使用此AppCompatDelegate在日间/夜间主题之间切换 我有两个活动A和B 此代码从活动B调用 它应该用所选择的风格重新创建活动B&A 这是我的密码 我在安卓7和6上测试了它,它工作得很好,即在活动B中更改模式,然后按回活动A,重新创建新主题。Android AppCompatDelegate.setDefaultNightMode未在Android 9中重新创建父活动,android,android-appcompat,android-night-mode,appcompatdelegate,Android,Android Appcompat,Android Night Mode,Appcompatdelegate,您好,我正在使用此AppCompatDelegate在日间/夜间主题之间切换 我有两个活动A和B 此代码从活动B调用 它应该用所选择的风格重新创建活动B&A 这是我的密码 我在安卓7和6上测试了它,它工作得很好,即在活动B中更改模式,然后按回活动A,重新创建新主题。 在android 9上试用时,它只改变了活动B,而不影响它的父活动A。我也遇到了这个问题,然后采纳了谷歌android开发者官方博客中Chris Banes的建议,首先在应用程序的应用程序类中设置setDefaultNightMod
在android 9上试用时,它只改变了活动B,而不影响它的父活动A。我也遇到了这个问题,然后采纳了谷歌android开发者官方博客中Chris Banes的建议,首先在应用程序的应用程序类中设置
setDefaultNightMode
,因此,我创建了一个类EcwgApplication extensing Application,如他所示,并在清单的Application
部分添加了android:name=“.EcwgApplication”
。我还将切换主题的方法放在应用程序类中,当用户更改主题设置时,我的设置活动可以调用该方法(除了在调用之前使用更改更新SharedReferences),因此它看起来如下所示:
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操作系统版本24到29中运行良好,但在21(该应用程序支持的最低版本)到23中,我在返回第一个活动时会看到一个黑屏,旋转屏幕可以解决这一问题,同时也清楚地表明UI状态没有被保存。因此,我将设置屏幕的StartActivity更改为StartActivityForResult,并在onActivityResult中检查版本号是否正确
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);
}
}