Reputation: 45
I want to create a style in a theme and use the values of it in code like this:
val bgColor = LIST_ITEM_BG_COLOR;
val textColor = LIST_ITEM_TEXT_COLOR
val strokeColor = LIST_ITEM_STROKE_COLOR
This is my theme file (theres also theme (night) file similar to this):
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.GuitarComposer" parent="Theme.Material3.DayNight.NoActionBar">
<!-- Customize your light theme here. -->
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
</style>
<style name="ListItem">
<item name="android:background">@color/component_background</item>
<item name="android:textColor">@color/text</item>
<item name="android:strokeColor">@color/border_color</item>
</style>
<style name="Theme.GuitarComposer" parent="Base.Theme.GuitarComposer" />
</resources>
I havent found any explanation on how to use theme styles properly in code.. only on xaml Hope someone could help me on this, thank you.
Upvotes: 0
Views: 42
Reputation: 45
After some very long investigating, I found out how to do it right:
val typedArr = context.obtainStyledAttributes(R.style.ListItem, arrayOf(android.R.attr.background).toIntArray())
val backgroundColor = typedArr.getColor(0,Color.GRAY)
Make sure you use android.R.attr and not something else like google or androidx.
A nice bonus is that even if this is on view initialization, switching between dark and light theme does work without need to restart the app!
Upvotes: 0
Reputation: 638
Try use this:
val typedValue = TypedValue();
theme.resolveAttribute(R.attr.strokeColor, typedValue, true);
val strokeColor = ContextCompat.getColor(this, typedValue.resourceId)
Upvotes: 0