kotlin detect dark mode

To detect dark mode in Kotlin, you can use the following steps:

  1. Get the system theme: Use the context.theme property to get the current theme of the system. This will allow you to determine whether the system is in dark mode or not.

  2. Get the current night mode configuration: Call the configuration.uiMode property to retrieve the current UI mode configuration. This will give you information about the current night mode setting.

  3. Check if night mode is enabled: Use the Configuration.UI_MODE_NIGHT_MASK constant to check if the night mode feature is enabled. This can be done by using bitwise AND operation with the configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK values.

  4. Determine the theme mode: If the result of the bitwise AND operation equals Configuration.UI_MODE_NIGHT_YES, it means that the system is in dark mode. You can then perform the necessary actions or apply the appropriate styling based on this information.

Here is an example code snippet that demonstrates the above steps:

// Step 1: Get the system theme
val systemTheme = context.theme

// Step 2: Get the current night mode configuration
val currentConfiguration = context.resources.configuration

// Step 3: Check if night mode is enabled
val isNightModeEnabled = currentConfiguration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES

// Step 4: Determine the theme mode
if (isNightModeEnabled) {
    // Perform actions or apply styling for dark mode
} else {
    // Perform actions or apply styling for light mode
}

By following these steps, you can effectively detect dark mode in Kotlin and adapt your application accordingly.