androidandroid-darkmode

I want to change the Android dark mode dynamically


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?


Solution

  • 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: