androidkotlindarkmodematerial3lightmode

Android Material3 toggle dark mode on click


I want to implement a switch for toggling dark mode in my application. After investigating multiple sources on how to do this correctly, I came across this one-line solution:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

Unfortunately, in my case this only changes the configuration to light mode and doesn't update UI colors. Here's my code:

binding.toggleDarkMode.setOnCheckedChangeListener { _, isChecked ->
   if (isChecked) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
      activity?.recreate()
   }
}

I'd also like to mention that I have separate theme files for light and dark mode. Light theme extends Theme.Material3.Light.NoActionBar and dark theme extends Theme.Material3.Dark.NoActionBar. Could anyone tell me what could be the problem?


Solution

  • So basically my phone's OS was overriding my app's styles on a MUI device. Here's the complete answer: Can't disable Night Mode in my application even with values-night