Dynamically pick up color

Asked

Viewed 55 times

0

I created some colors in the file colors.xml

<color name="colorBackground1">#5c6bc0</color>
<color name="colorBackground2">#1e88e5  </color>
<color name="colorBackground3">#00838F</color>

In the adapter I want to set the color dynamically

val cor = "R.color." + cores.get(position)
val colorValue = getColor(context, cor)
vh.item.setBackgroundColor(colorValue)

The variable corescontains only the name of the color, example colorBackground1. But on the line
val colorValue = getColor(context, cor)

it does not accept the variable cor, expecting a int but there’s a string and couldn’t find a way to convert. The string comes out with the right name, R.color.colorBackground1. How to solve?

1 answer

0


Or you can transform val cor = "R.color." + cores.get(position) in one piece.

or ideally use the following method:

getResources().getIdentifier("name", "resource", "package");

In your case I would then:

val cor = getResources().getIdentifier(cores.get(position), "color", getPackageName());

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.