Skip to content
Advertisement

How to save dark mode state in android when the app is completely closed

I have a little problem. When I turn on dark mode in my app and then close my app completely in android, when I reopen it, it returns to light mode. I use AppCompatDelegate to do this. I have a settings fragment with a switch to turn on or off dark mode and it works well. I have a shared preferences on that fragment for the switch and it works. The only problem is that the rest of the application doesn’t stay in dark mode after being completely closed the reopened after. Is there a way I can save and then restore the dark mode when I close the reopen it?

Here’s my code for MainActivity:

JavaScript

Here’s my code for SettingsFragment:

JavaScript

Advertisement

Answer

I found an easy and straight forward answer. I tested it multiple times to make sure. Just add the following variables in MainActivity:

JavaScript

After that, you’ll want to add the following lines in MainActivity’s OnCreate() method:

JavaScript

And to finish it off, save all of your variables in your shared preferences using the OnSaveInstanceState method:

JavaScript

That’s all you need to do to save the dark mode state of your whole app even when the app is terminated or killed by the OS.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement