I want to change the Android dark mode dynamically

611 Views Asked by At

In my Android project currently under development, there are many Fragments in Activity. And inside the Fragment, RecyclerView is used to show multiple Items to the user.

What I want is that when the user changes the dark mode or light mode in the status bar, the dark mode is applied without exiting the app. What should I do?

1

There are 1 best solutions below

1
On BEST ANSWER

Given a Configuration, you can find out whether the device is in dark mode by examining uiMode:

val currentNightMode = configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
when (currentNightMode) {
    Configuration.UI_MODE_NIGHT_NO -> {} // Night mode is not active, we're using the light theme
    Configuration.UI_MODE_NIGHT_YES -> {} // Night mode is active, we're using dark theme
}

(source code from the documentation)

You can get a Configuration:

  • At the point of a configuration change, by opting out of uiMode in the manifest and overriding onConfigurationChanged() in your activity, or
  • At any point by calling getResources().getConfiguration() on a Context, such as your Activity