Android 10 or above introduced a new feature: Dark theme. Dark theme applies to both the Android UI and apps (support dark mode) running on the device. Android 10 gave a system-level option that switches between dark and light themes.
It has many benefits:
- Can reduce power usage (depending on the device’s screen technology).
- Improves visibility for users with low vision and those who are sensitive to bright light.
- Makes it easier for anyone to use a device in a low-light environment.
Let’s begin
1. App Level Dependencies
First you need to add the material design dependency to your app-level build.gradle file
1 | //Material Design |
2. Declare Themes
Till now we have the parent theme as:
1 | <style name="Base.AppTheme.MyAppName" parent="Theme.MaterialComponents.DayNight.NoActionBar"> |
Basically, a DayNight theme is composed of a Light theme in the values directory and a Dark theme in the values-night directory.
Create the night resource files under res/values-night/themes.xml
Add light theme in res/values/themes.xml
1 | <style name="Theme.MaterialComponents.DayNight.NoActionBar.Bridge." parent="Theme.MaterialComponents.Light.NoActionBar.Bridge"> |
Add dark theme in res/values-night/themes.xml
1 | <style name="Theme.MaterialComponents.DayNight.NoActionBar.Bridge." parent="Theme.MaterialComponents.NoActionBar.Bridge"> |
And then, declare your AppTheme in res/values/themes.xml
, where parent theme will be yours dark/light theme
1 | <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge"> |
Now add colors files for both dark and light theme:
For light theme add colors in res/values/colors.xml
1 | <color name="colorPrimary">#fff5f5f5</color> |
And for dark theme add colors in res/values-night/colors.xml
1 | <color name="colorPrimary">#ff212121</color> |
3. Allow users to change the app’s theme programmatically
Use the following code in your Activity to change the app mode between dark and light.
1 | button.setOnClickListener { |
That’s it, run your app and enjoy a dark theme!
References
Some good reads you may like:-
p.s. Nayan is a platform that offers high precision services for traffic monitoring and road safety. Check out our website