How to Enable Night Mode Programmatically

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

Can't disable Night Mode in my application even with values-night

I had the same issue on my Xiaomi Redmi Note 7. I tried this code inside MainActivity.create():

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

But it doesn't work on some of Xiaomi devices including mine, though it works on other phones.

So the only solution I've found is to add <item name="android:forceDarkAllowed" tools:targetApi="q">false</item> to each of your AppTheme in styles.xml. Like this:

<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
</style>

It worked fine for my phone.

Enable android:forceDarkMode programmatically?

You can programmatically enable the dark theme on Android Q with the following code:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);



Related Topics



Leave a reply



Submit