Android AppCompatDelegate.setDefaultNightMode 不在 android 9 中重新创建父 Activity

标签 android android-appcompat android-night-mode appcompatdelegate

您好,我正在使用此 AppCompatDelegate 在日/夜主题之间进行切换
我有 2 项 Activity A&B
此代码从 Activity B 调用
它应该用所选风格重新创建 Activity 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 上对其进行了测试,它工作正常,即在 Activity B 中更改模式并按下 Activity A 重新创建新主题时。
在 android 9 上尝试它时,它只改变了 Activity B 而不会影响它的父 Activity A。

最佳答案

我也遇到了这个问题,然后在 Google 的官方 Android 开发者博客 https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94 中听取了 Chris Banes 的建议。设置setDefaultNightMode首先在应用程序的应用程序类中,所以我创建了一个类 EcwgApplication 扩展应用程序,如他所示,并添加了 android:name=".EcwgApplication"application list 的一部分。我还将用于切换主题的方法也放在了应用程序类中,当用户更改主题设置时,我的设置 Activity 可以调用(除了在调用它之前使用更改更新 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,我会在返回第一个 Activity 时出现黑屏,并且在旋转屏幕时会解决这个问题,它也使清除未保存 UI 状态。所以我将设置屏幕的 StartActivity 更改为 StartActivityForResult,并在 onActivityResult 中检查版本号是否 <= 23,如果是,则执行 this.recreate() .

我需要继续做更多的测试,但至少到目前为止一切似乎都很好。

关于Android AppCompatDelegate.setDefaultNightMode 不在 android 9 中重新创建父 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60138485/

相关文章:

android - 游标遍历空行

android - 如何在夜间模式下更改深色操作栏的颜色?

android - 如何以编程方式启用夜间模式?

android - 对 sqlite 记录进行分组和排序

android - ClickableSpan 避免触摸传播到父 View

安卓openCV

java - 删除默认操作栏选项卡填充

java - 如何修复 java android 中的 LayoutInflater 错误?

android - 我可以将 AppCompat 主题与 Activity/FragmentActivity 类一起使用吗?

Android - 使用 AppCompatDelegate.MODE_NIGHT_AUTO 时如何检测夜间模式是否打开