light theme
After that, we need to change the android style to (in my case)
Or to the material component:
Now let’s go to the MainActivity Class and create the method chooseThemeDialog and inside add the code to create an AlertDialog, to allow the user to choose the theme.
In the onCreate method let’s call the chooseThemeDialog method when the user clicks on the button
Run the app again and let’s see the result🧐 when we click on the button
light theme
So, let’s go inside to chooseThemeDialog method and add the code to change the theme and apply to our App using the when condition and AppCompatDelegate.
AppCompatDelegate is a class in support library of android that allows us to work with Dark Theme implementation. for that's work we will com a static method call setDefaultNightMode and pass the mode as a parameter, like:
- AppCompatDelegate.MODE_NIGHT_NO: means night mode is not active, we’re using the light theme
- AppCompatDelegate.MODE_NIGHT_YES: means night mode is active and we’re using dark theme
- AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM: means we will follow the system definition
Run the app and check the result when we click on dark on the AlertDialog
dark theme
But we can improve the code, by saving the choice of the user, in this case, we can use SharePreferences for this.
For it works, we need do added the new SharedPreferences dependency to the build.gradle file.
Let’s create the class MyPreferences to help us manipulate and store the value on the SharedPreferences.
Now we can update our chooseThemeDialog method to save the choice of the user and keep the theme even when we close the app
Create also the checkTheme method to check on the onCreate method what theme status we saved on SharedPreferences
Now as we already said, we need to call the checkTheme method inside the onCreate.
Now the final result🎉
App Demo
So, that is it for now, and don’t forget to see the full code on my Github
manuelernesto/darkmode_app_with_kotlinContribute to manuelernesto/darkmode_app_with_kotlin development by creating an account on GitHub. |
![]() |
Thanks to you for reading this post! Please do 👏🏿 if you liked it and want more posts about android development.