Updated 29 June 2020
Dark theme in Android: displays dark surfaces across the majority of a UI. It’s designed to be a supplemental mode to default (or light) theme.
Dark theme is available in Android 10 (API level 29) and higher. It has many benefits:
1 |
<style name="AppTheme" parent="Theme.AppCompat.DayNight"> |
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.We recommend using Material Design Components, since its color theming system (such as the theme attributes ?attr/colorSurface
and ?attr/colorOnSurface
) provides easy access to suitable colors. Of course, you can customize these attributes in your theme.
When running on devices running Android 9 or earlier, the recommended theme options are:
When running on Android 10 (API level 29) and higher, 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().
Let’s do some real code:
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 |
public class Helper { 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()) {If your app has a custom launch screen, it may need to be modified so that it reflects the selected theme.Remove any hardcoded colors, for example, any background colors pointing may be white. Use the ?android:attr/colorBackground theme attribute instead.Note that dark-themed android:windowBackground drawables only work on Android Q. AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY); } break; } } } |
?android:attr/colorBackground
theme attribute instead. Note that dark-themed android:windowBackground
drawables only work on Android Q.If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.