天天看點

擷取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)
}
           

使用