Night Mode Implementation in Android

rumi rajbhandari
3 min readApr 30, 2020

--

Easiest way to implement night mode in android.

Photo by Nathan Anderson on Unsplash

Android has recently introduced Dark theme from Android 10 which allows user to easily toggle between light/dark theme. Since then many popular applications have been updated to support dark theme. So we in our company too decided to give it a go in our new application.

Follow the article to support dark mode in your application and also to learn how we implemented it in our app.

Before starting make sure to update your appcompact to the latest version.

implementation 'androidx.appcompat:appcompat:1.1.0'

Updating Theme

To enable dark mode you must implement your theme from DayNight.

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

Switching the Theme

Now to switch the mode just call the method AppCompatDelegate.setDefaultNightMode() which takes any one of the following 4 arguments:

  • MODE_NIGHT_NO : uses light mode
  • MODE_NIGHT_YES : uses dark mode
  • MODE_NIGHT_FOLLOW_SYSTEM : uses system’s night mode setting to determine if it is night or not
  • MODE_NIGHT_AUTO_BATTERY : uses dark mode when system’s battery saver is enabled
AppCompatDeegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

The above function will enable dark mode in your app. However, it uses default theme of your device. You might want to further customize your application by defining your own attributes for dark mode.

Colors

Create a new colors resource file inside a new android resource directory called values-night. Your folder will look something like this

Drawables

Create a separate drawable folder named drawable-night to define images for dark mode.

In our application we have tons of icons and creating new icons specifically for dark mode seemed some what tedious. So I modified the fillColor of the icons to my custom defined iconColor which has defined in both of my colors resources.

<path
android:fillColor="@color/iconColor"
.../>

To use dynamic coloring in icons the minSdkVersion must be 21 or greater.

Persisting

At this point, you will be able to change your app into dark/light mode. However once you restart your app, it will revert back to the light mode. So in other to display the selected mode, you have to save the user’s choice and update your UI accordingly during the app start up. It is done in onCreate method of the application file.

Note: You can update dark/light mode from your activity. However updating it in the activity recreates the activity. So it is recommended to update the mode in the application file.

And Voila..

You can now enjoy night mode in your application.

Github sample for the night mode.

https://github.com/RumiRajbhandari/NavigationComponentDemo.git

--

--