Updated 25 July 2019
A dark theme is a low-light UI that displays mostly dark surfaces.
Dark theme has many benefits:
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:
When running on Android Q, the recommended options are different, to allow the user to override the system default:
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:
MODE_NIGHT_NO
MODE_NIGHT_YES
MODE_NIGHT_AUTO_BATTERY
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:
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.