从Theme.MaterialComponents.DayNight.DarkActionBar中提取昼夜资源。

问题描述 投票:0回答:1

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

material-design android-theme
1个回答
0
投票
@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()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.