A dark theme is a low-light UI that displays mostly dark surfaces.
Dark theme has many benefits:
- Can reduce power usage by a significant amount (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.
To support dark theme you need to inherit DayNight
theme:
1 |
<style name="AppTheme" parent="Theme.AppCompat.DayNight"> |
You can also use MaterialComponents’ dark theming:
1 |
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight"> |
Here are the two most important theme attributes to know about:
?android:attr/textColorPrimary
This is a general purpose text color. It is near-black in Light theme and near-white on Dark themes. It contains a disabled state.?attr/colorControlNormal
A general-purpose icon color. It contains a disabled state.
On devices running Android 9 or earlier, the recommended theme options are:
- Light
- Dark
- Set by Battery Saver (the recommended default option)
When running on Android Q, the recommended options are different, to allow the user to override the system default:
- Light
- Dark
- System default (the recommended default option)
Note that if the user selects Light, then Battery Saver will not change that setting.
Each of the options map directly to one of the AppCompat.DayNight
modes:
- Light –
MODE_NIGHT_NO
- Dark –
MODE_NIGHT_YES
- Set by Battery Saver –
MODE_NIGHT_AUTO_BATTERY
- System default –
MODE_NIGHT_FOLLOW_SYSTEM
To switch the theme, call AppCompatDelegate.setDefaultNightMode().
You can create a helper class like below to toggle the Dark Mode :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class ThemeHelper { public static final String LIGHT_MODE = "light"; public static final String DARK_MODE = "dark"; public static final String DEFAULT_MODE = "default"; public static void applyTheme(@NonNull String themePref) { switch (themePref) { case LIGHT_MODE: { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); break; } case DARK_MODE: { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); break; } default: { if (BuildCompat.isAtLeastQ()) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY); } break; } } } } |
References: