天天看点

获取Theme中Attr属性的Color值

前言

在做多套主题切换时,个别View是在代码中创建的,切换不同主题时,无法直接获取到自定义的 attr 属性的 color 值,在网上看了大多数使用新建一个 TypedValue 对象,然后使用 context.theme.resolveAttribute 函数将color值复制到 TypedValue 对象中,通过 typedValue.data 的方式获取,但是这种仅仅局限于当前上下文环境下的 Theme 属性,切换其他 Theme 后就不会生效,翻看了下 Material 的包,发现源码中已经提供了现成的函数给我们使用。

Theme定义

继承 Theme.MaterialComponents.DayNight.NoActionBar 主题,自定义 colorAccent 属性色值。

<style name="AppTheme.NoActionBar" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="textAllCaps">false</item>
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        
        <!--省略其他属性-->
        
        <item name="colorAccent">#546e7a</item>
    </style>
           

返回 ColorInt 类型值

@ColorInt
fun getThemeAttrColor(@NonNull context: Context, @StyleRes themeResId: Int, @AttrRes attrResId: Int): Int {
	return MaterialColors.getColor(ContextThemeWrapper(context, themeResId), attrResId, Color.WHITE)
}
           

返回 ColorStateList 类型值

fun getThemeAttrColor(@NonNull context: Context, @StyleRes themeResId: Int, @AttrRes attrResId: Int): ColorStateList {
	val color = MaterialColors.getColor(ContextThemeWrapper(context, themeResId), attrResId, Color.WHITE)
	return ColorStateList.valueOf(color)
}
           

使用