android - 如何在不重新加载 fragment 的情况下应用夜间模式?

标签 android

我在我的 android 项目中使用了灯光/夜间模式,并在 fragment 中使用了一个开关来更改模式。好吧,当我重新加载应用程序时它会改变。但我想在不重新加载应用程序的情况下更改模式。我怎样才能做到这一点???

  • 我想在更改模式时保留当前 fragment 。
    aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b){
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                aSwitch.setChecked(true);
                sh = getActivity().getSharedPreferences("darklight",Context.MODE_PRIVATE).edit();
                sh.putBoolean("is",true);
                sh.commit();
            }else{
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                sh = getActivity().getSharedPreferences("darklight",Context.MODE_PRIVATE).edit();
                sh.putBoolean("is",false);
                sh.commit();
            }
        }
    });
    
  • 最佳答案

    您可以通过在 Android 中使用 AppCompatDelegate 命令轻松完成此操作
    将其设置为 False

    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    
    将其设置为 True
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    
    此外,您还可以使用切换按钮来应用修改和模式之间的切换。

    关于android - 如何在不重新加载 fragment 的情况下应用夜间模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59191354/

    相关文章:

    java - MediaRecorder 启动Android 7.1.1 模拟器失败

    android - 从 ListView 中单击的项目获取字符串值

    android - 在 Android 4.3 中加载内核模块

    android - 在 Android Webview 上使用 <Embed> 标签播放 mp4 视频

    android - 如何在 Android 中创建带有边和顶点的图

    java - 如何将 JSON 数组解析为 Android 列表

    android - 在 android.arch.navigation :navigation-ui-ktx 中找不到新的 <dialog> 标签

    android - 在不显示选择器的情况下启动 native 相机

    android - 如何在android中为一个对象设置多个标签

    android - ListView 和选项菜单