How to enable night mode programmatically?

SIMPLEST SOLUTION

You can enable/disable application’s dark theme just by:

  1. enable dark theme:

     AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    
  2. forcefully disable dark theme:

     AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    
  3. set app theme based on mobile settings of dark mode, i.e. if dark mode is enabled then the theme will be set to a dark theme, if not then
    the default theme, but this will only work in version >= Android version Q (10)

     AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
    

Notes:

  1. Your base theme for app/activity should be

“Theme.AppCompat.DayNight”

like

<style name="DarkTheme" parent="Theme.AppCompat.DayNight">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
  1. Your res folder’s names would end with -night so that different colors and images you can set for day and night themes like

drawable & drawable-night,
values & values-night

Leave a Comment