How can I set dark Mode on my app with the switch

540 Views Asked by At

I know it might be easy but is just something that I don't really know. I am new at coding and I tried different codes in my app.

The code that I currently used does nothing:

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

I don't know if this is the one that is meant to do its thing or not. I just want a code that should solve my problem.

This is the night theme in my values:

<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>

Thank you in advance.

2

There are 2 best solutions below

0
On

To enable night mode use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); and to disable it use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);.

0
On

you can do this as following:

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

and it's better to save this isChecked in Shared preferences and restart your app and in each activity before call super.onCreate() in onCreate() method just check this flag and do the following:

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