In my values
folder I have my_colors.xml
:
<resources>
<!-- Orange -->
<color name="orangePrimary">#f6a02d</color>
<color name="orange1">#e3952a</color>
<color name="orange2">#da8f28</color>
<color name="orange3">#d08926</color>
</resources>
Is there a way to get these colors just with the string of its name?
Something like view.setBackgroundColor.getColor("orange1");
For images you have this getResources().getIdentifier("my_image", "drawable", getPackageName());
Hope you guys know what I mean. Greetings.
A colour string is a group of premixed piles of paints with different tonal values. You usually start with the darkest colour in the string (say a pure ultramarine blue) and slowly add progressively lighter 'steps' to the mixture.
Syntax: System. out. println(ANSI_COLORNAME + "This text is colored" + ANSI_RESET);
Have you tried the following:
// java
Resources res = context.getResources();
String packageName = context.getPackageName();
int colorId = res.getIdentifier("my_color", "color", packageName);
int desiredColor = res.getColor(colorId);
// kotlin
val res: Resources = context.getResources()
val packageName: String = context.getPackageName()
val colorId: Int = res.getIdentifier("my_color", "color", packageName)
val desiredColor: Int = res.getColor(colorId)
Hope it helps!
Note: This is deprecated, instead you could do the following, which handles both pre and post Marshmallow (API 23):
// java
Resources res = context.getResources();
String packageName = context.getPackageName();
int colorId = res.getIdentifier("my_color", "color", packageName);
int desiredColor = ContextCompat.getColor(context, colorId);
// kotlin
val res: Resources = context.getResources()
val packageName: String = context.getPackageName()
val colorId: Int = res.getIdentifier("my_color", "color", packageName)
val desiredColor: Int = ContextCompat.getColor(context, colorId)
Okay, I got the color by name using reflection now and got this working in my side.
You need to write a function like this.
public int getColorByName(String name) {
int colorId = 0;
try {
Class res = R.color.class;
Field field = res.getField(name);
colorId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
return colorId;
}
Now get the resource id using
int resourceId = getColorByName("orange1");
And set the drawable as a resource in your ImageView
like this.
imageView.setBackgroundResource(resourceId);
I tried setting img.setBackgroundColor(resourceId)
which was setting the wrong color.
In your case I would like to suggest to keep the colors in a typed array in your res/values/arrays.xml
like this
<array name="colors">
<item>#FFFF0000</item>
<item>#FF00FF00</item>
<item>#FF0000FF</item>
</array>
See the developers doc for Typed Array about how to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With