如何使用开关在我的应用程序上设置暗模式

问题描述

我知道这可能很容易,但只是我真的不知道。我是编码新手,我在我的应用中尝试了不同的代码

我目前使用的代码没有任何作用:

aSwitch.setonCheckedchangelistener(new CompoundButton.OnCheckedchangelistener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            if (isChecked){
                switch (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) {
                    case Configuration.UI_MODE_NIGHT_YES:
                    case Configuration.UI_MODE_NIGHT_NO:

                        break;
                }
            }
        }
    });

我不知道这是不是应该做它的事情。我只想要一个可以解决我的问题的代码

这是我价值观中的夜间主题

<style name="Theme.Diligent" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/black</item>
    <item name="colorPrimaryVariant">@color/black</item>
    <item name="colorOnPrimary">@color/white</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">@color/black</item>
    <item name="colorSecondaryVariant">@color/black</item>
    <item name="colorOnSecondary">@color/white</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
 </style>

提前致谢。

解决方法

要启用夜间模式使用 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);,禁用它使用 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

,

你可以这样做:

sw_exclusive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton,boolean isChecked){ 
if (isChecked){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } } });

并且最好在共享首选项中保存此 isChecked 并重新启动您的应用程序和在 onCreate() 方法中调用 super.onCreate() 之前的每个活动中,只需检查此标志并执行以下操作:

if (isChecked){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); }
,

所以我这样做了,按下开关后什么也没发生:

aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            if (isChecked){
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); }
        }
    });

大家有什么建议吗?