In kotlin android development how to check if theme is in dark or light mode ?
- User
In kotlin android development how to check if theme is in dark or light mode ?
- Assistant
In Kotlin Android development, determining whether the current theme is in dark or light mode is essential for providing a consistent user experience. There are several approaches to achieve this, depending on your project's requirements and the Android API level you are targeting. Below are the most common methods:
1. Using the
ConfigurationClassThe
Configurationclass provides information about the current configuration, including the UI mode (light or dark). You can access this information via theresources.configurationproperty.Implementation:
kotlinimport android.content.Context import android.content.res.Configuration fun isDarkModeEnabled(context: Context): Boolean { val uiMode = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK return when (uiMode) { Configuration.UI_MODE_NIGHT_YES -> true Configuration.UI_MODE_NIGHT_NO, Configuration.UI_MODE_NIGHT_UNDEFINED -> false else -> false } }Usage:
kotlinval darkMode = isDarkModeEnabled(this) // 'this' refers to a Context, such as an Activity if (darkMode) { // Dark mode is enabled } else { // Light mode is enabled }2. Using
AppCompatDelegateIf your project uses AppCompat, you can leverage
AppCompatDelegateto determine the current night mode. However, it's essential to note thatAppCompatDelegate.getDefaultNightMode()returns the default mode set for the app, which might not always reflect the current system setting.Implementation:
kotlin