The dark mode, perhaps is one of the easiest functionality to implement without breaking literally anything in existing project. However, it has it's own hidden costs, tricks. Before implementing the Dark mode, what is most important is that your project must be ready for dark mode.
What I had:
What I wanted to achieve:
The only thing you need to do to get your app ready for dark mode is the themes tag and the AppCompatDelegate class. The rest depends on your project. So instead of some <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> you just need the <style name="AppTheme" parent="Theme.AppCompat.DayNight"> . The code for dark mode/light mode is pretty simple:
Note: These are not the only states.
The problems I faced:
First of all, if you notice the drawer on the Light mode, you will see that the text of the menu items, is black. I don't really want that, because in dark mode it will truly suck. Since you cannot change it from xml, here is what you can do for it:
Custom inserted colors:
There is two options in this part of the problem. Well, my background colors or my text colors had a color set by the xml and not by the theme. So what you can do here is choose colors that don't really affect the visibility on theme change, or leave Androids default.
Since I am using a single Activity and making these changes in the activity (because the drawer is located there) there is no more need to handle things in fragments (except when having to replace an icon depending on the theme).
Yes. We should be careful with the toolbar. Once you implement the dark theme, you may not want your toolbar to have a black text as well. So you just change it's behavior to:
One mistake I used to make during my implementation was that I tried to recreate() the activity in order for the onSavedInstanceState to be called. No need for that, once you call AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.WHATEVER_MODE) the activity will recreate for you. Once the activity is recreated, in your onCreate method you can check for the drawer or toolbar as discussed above.
Is there a better approach?
Perhaps yes. You may try to code all this from the theme tag on the styles.xml. But since xml is not my thing, I chose this approach.
Hope I helped. Full project on Github.