Possible to get color with string?

一曲冷凌霜 提交于 2019-12-23 16:55:12

问题


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.


回答1:


Have you tried the following:

int desiredColour = getResources().getColor(getResources().getIdentifier("my_color", "color", getPackageName()));

Hope it helps!




回答2:


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.




回答3:


Starting from Android Support Library 23, a new getColor() method has been added to ContextCompat.

So, just call:

ContextCompat.getColor(context, R.color.your_color);

The other one is depracated getResources.getColor() So you need to implement the above. No any way for just passing the name of color to access it. you have to give color id from your color file.



来源:https://stackoverflow.com/questions/39817299/possible-to-get-color-with-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!