1

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

我目前使用的代码什么都不做:

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>

先感谢您。

4

3 回答 3

0

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

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); }
        }
    });

你们有什么建议吗?

于 2021-03-06T09:37:01.930 回答
0

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

于 2021-03-05T18:12:55.237 回答
0

你可以这样做:

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); }
于 2021-03-05T19:22:55.203 回答