How can I assign a specific color according to whether night mode is activated or not on the device?

16 Views Asked by At

I need to display a large amount of text in a textView, of which certain parts must be red when the device is in day mode and amber when the device is in night mode.

Since I do not have access to the context when the text content is generated, I have created a utility class called ColorUtils and a property isNightMode, to choose the color that should be applied to the texts:

var isNightMode = false
val redCode: String
    get() = if (isNightMode) "#FFDAB9" else "#A52A2A"

In the Manifest I have added the value uiMode to configChanges and in the fragment I have this:

override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
        Configuration.UI_MODE_NIGHT_NO -> {
            ColorUtils.isNightMode = false
        }
        Configuration.UI_MODE_NIGHT_YES -> {
            ColorUtils.isNightMode = true
        }
    }
}

enter image description here

The code does not always work as expected, as you can see in the reproduction above.

This is what happens:

  • The sequence starts in day mode. Everything correct: color of the top bar blue, background color of the screens with Recyclerview blue and partial text color in red.

  • I make a first change to night mode and the following happens: background color of the Recyclerview is fine, it is black, but color of the top bar is blue when it should be black. Same problem on the other two screens that follow. Also the partial text, which should have changed to amber, remains in red.

  • Then I go back to day mode and everything is still correct in that mode.

  • Finally, I go back to night mode. And the color of the partial text is now correct, it appears amber, but the color of the top bar never turns black, remaining blue.

Why is this happening and how could I resolve it from the first switch from day mode to night mode?

0

There are 0 best solutions below