Home > Back-end >  How to get color which is defined as attribute for different themes in Android [Kotlin]
How to get color which is defined as attribute for different themes in Android [Kotlin]

Time:09-15

In my case I have defined a scenario I have a FAB and I want it to have three different colors across three different themes ( I have 3 themes - dark, light, plain).

So I am using the attribute and changing the colors of FAB across all the themes (for the same attribute). Now I want to do this thing programmatically and not through xml.

So I want a way so that I can access that attribute inside my activity and then fetch the color from attribute and set it as background color of FAB (based on different themes)

P.S - I have checked few answers on SO already but they are not helpful in my case. The issues are they are for text views and not fab, and sometimes it feels like a lot of boilerplate code.

If you have any understanding of how to resolve this please let me know. Thanks!

CodePudding user response:

I tested this and it works for me:

val color = MaterialColors.getColor(context, R.attr.myColor, Color.GRAY)
binding.fab.backgroundTintList = ColorStateList.valueOf(color)

This ^^^ is btw from SO, specifically from this answer and its comments: Get color value programmatically when it's a reference (theme).

  • Related