我用的是 Theme.MaterialComponents.DayNight.DarkActionBar
作为我的应用程序的主题,并希望以编程方式获得,例如。android.R.attr.textColorPrimary
暗模式和亮模式的颜色。这可能吗?如果可以,怎么做?
@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()
}
}