android - Android AppCompatDelegate.setDefaultNightMode 不在 android 9 中重新创建父活动
问题描述
您好,我正在使用此 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 开发者博客https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94setDefaultNightMode
中听取了 Chris Banes 的建议,首先在应用程序的应用程序类中进行设置地方,所以我创建了一个类 EcwgApplication 扩展 Application 如他所示,并添加到清单android:name=".EcwgApplication"
的application
部分。我还将用于切换主题的方法也放在了应用程序类中,当用户更改主题设置时,我的设置活动可以调用(除了在调用它之前使用更改更新 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 中检查版本号是否 <= 23,如果是,请执行this.recreate()
.
我需要继续做更多的测试,但至少到目前为止一切似乎都很好。
推荐阅读
- c# - 如何在 C# 中反序列化动态命名的 JSON?
- javascript - 如何使用按钮单击平滑淡入淡出切换文本?
- python - UnboundLocalError:在为循环赋值之前引用的局部变量
- xml - 需要将日期与斜线类型进行比较
- r - 如何将类似样式的标签添加到 facet_grid
- ssrs-2017 - X 轴条形图底部支架
- microsoft-graph-api - 如何使用 Microsoft Graph 获取 Microsoft 365 Planner“所有用户的所有计划”
- docker - Docker 统计 API 总 CPU
- python - np.linalg.det() 是计算矩阵行列式的独特方法吗?
- javascript - 类型 'unknown' 不可分配给类型 '(prevState: number | undefined) => number | 不明确的'