Search code examples
material-designandroid-theme

Extract day/night resources from Theme.MaterialComponents.DayNight.DarkActionBar


I'm using Theme.MaterialComponents.DayNight.DarkActionBar as my app's theme and would like to programmatically get, for example, the android.R.attr.textColorPrimary color for both dark mode and light mode. Is this possible? If so, how?


Solution

  • @ColorInt
    fun getStyledDayNightColor(context: Context, @AttrRes attrResId: Int, night: Boolean): Int {
        val configuration = Configuration(context.resources.configuration).apply {
            uiMode = if (night) {
                Configuration.UI_MODE_NIGHT_YES
            } else {
                Configuration.UI_MODE_NIGHT_NO
            }
        }
        val contextWrapper = ContextThemeWrapper(context, R.style.Theme_MaterialComponents_DayNight).apply {
            applyOverrideConfiguration(configuration)
        }
        val ta = contextWrapper.obtainStyledAttributes(intArrayOf(attrResId))
        return ta.getColor(0, Color.GREEN).also {
            ta.recycle()
        }
    }