Dark theme is available in Android 10 (API level 29) and higher. There are three ways to enable Dark theme in Android 10 (API level 29) and higher:
- Use the system setting (Settings -> Display -> Theme) to enable the Dark theme.
- Use the Quick Settings tile to switch themes from the notification tray (once enabled).
- On Pixel devices, selecting the Battery Saver mode enables the Dark theme at the same time. Other OEMs may or may not support this behavior.
Supporting Dark theme in your app
In order to support the Dark theme, we need to set the app themes to inherit from a DayNight theme.
Changing themes in-app
As suggested by Google, we should allow users to change the app’s theme while the app is running. The application can let the user choose between themes.
When running on devices running Android 9 or earlier, the recommended theme options are:
- Set by Battery Saver (the recommended default option)
When running on Android 10 (API level 29) and higher, the recommended options are different, to allow the user to override the system default:
- System default (the recommended default option)
Note: that if the user selects Light, then Battery Saver will not change that setting.
Android 10 provides Force Dark, a feature to quickly implement a Dark theme without explicitly setting a DayNight theme as mentioned above.
Force Dark analyzes each view of your light-themed app and applies a dark theme automatically before it is drawn to the screen.
Apps must opt-in to Force Dark by setting android:forceDarkAllowed=” true” in the activity’s theme.
Note: If our app uses a dark theme (such as Theme.Material), Force Dark will not be applied. Similarly, if your app’s theme inherits from a DayNight theme, Force Dark will not be applied, due to the automatic theme switching.
When the app’s theme changes (either through the system setting or AppCompat) it triggers a uiMode configuration change. This means that Activities will be automatically recreated.
An app can handle the implementation of the Dark theme itself by declaring that each Activity can handle the uiMode configuration change.
Points to Remember while Implementing Dark Theme:
Never hard-code any colors in the layout file
To implement dark/light mode create a values-night & drawable-night folder for helping OS to pick the images/colors from these folders when implementing dark mode.
When the theme change occurs, activity is destroyed and recreated again. This might lead to unexpected results in case if any API/data operation is in progress on a background thread. This can be handled during the configuration change callback.
Separate drawable resources are advised for Dark/Light mode for better user experience.
You can find the simple demonstration of the concept here