DEV Community

Cover image for How to add the DayNight Theme to an Android app using Kotlin
Nwokocha wisdom maduabuchi
Nwokocha wisdom maduabuchi

Posted on

How to add the DayNight Theme to an Android app using Kotlin

The DayNight functionality in AppCompat allows your app to easily switch between a dark ⚫ and light ⚪ theme.
Also, the DayNight theme gives an app the cool capability of switching color schemes based on the time of day and the device's last known location.

Benefits of DayNight Theme

1: Saves battery life
2: reduce the risk of damaging the eyes
3: easily accessible at night
4: increasing usability for people with reduced-vision

Learn to use Androidx DayNight Theme

Step 1 ) Update styles.xml

<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">

The themes you can extend from to add day night theme switching capability are the following:

"Theme.AppCompat.DayNight"
"Theme.AppCompat.DayNight.NoActionBar"
"Theme.AppCompat.DayNight.DarkActionBar"

Step 2 ) Update MainActivity code

To switch the theme, call the AppCompatDelegate.setDefaultNightMode(int) method from your Kotlin code. (This will change the color scheme for the whole app, not just any one activity or fragment.) For example:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

Note:

AppCompatDelegate.MODE_NIGHT_NO:
this sets the default theme for your app and takes the colors defined in the res/values directory. It is recommended to use light colors for this theme.

AppCompatDelegate.MODE_NIGHT_YES:
this sets a night theme for your app and takes the colors defined in the res/values-night directory. It is recommended to use dark colors for this theme.

AppCompatDelegate.MODE_NIGHT_AUTO:
this auto switches the colors of the app based on the time of the day and the colors you have defined in values and values-night directories.

Note:

however, that the theme switch will not persist if you kill the app and reopen it. If you do that, the theme will switch back to AppCompatDelegate.MODE_NIGHT_AUTO, which is the default value. If you want the theme switch to persist, make sure you store the value in shared preferences and load the stored value each time the app is opened after it has been destroyed.

GitHub

Top comments (0)