0

Basically what I'm trying to achieve is to access from code two related resources.

Consider this example, the best solution I can think of to my problem:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="black">⬛</string><color name="black_c">#000000</color>
    <string name="white">⬜</string><color name="white_c">#ffffff</color>
</resources>

Given a string N in my code I can access both the second string associated to it (⬛ or ⬜) or the color by adding "_c" to the end of the N string.

So, if N="black" I can use N to retrieve both ⬛ and #000000 (with N + "_c")

Is there a better way to do this? My solution feels a bit hacky. Hope I managed to explain what I'm trying to achieve, thanks!

Bonfi
  • 121
  • 1
  • 9

2 Answers2

1

I have another proposal. I hope it will help you.

If you have a colors.xml and a strings.xml (within the values directory)

<!-- colors.xml -->
<resources>
    <color name="black">#000000</color >
</resources> 

<!-- strings.xml -->
<resources>
    <string name="black">Some black string</string>
</resources> 

Using the same name you can access both of them if you are able to get the different id (ie R.string.black or R.color.black). The getIdentifier()` method can do it. So you can try (not tested)

String name = "black;
String choice = "color"; //or "string" dependending on if you want the color or the string
int resID = getResources().getIdentifier(name, choice, getPackageName());
Resources resources = getResources();

//Then access using
//If choice=="color"
int color = resources.getColor(resId);

//If choice=="string"
String text = resources.getString(resId);
Bonfi
  • 121
  • 1
  • 9
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • Thanks! Didn't thought about this, it's way better than my solution. I corrected one of the xml files name in your answer. – Bonfi Oct 19 '15 at 14:09
0

Ya it sounds a bit hacky. You could use styles to group all your resources (as attributes to that style) and then read those styles. More info here: How to retrieve style attributes programmatically from styles.xml

But this again sounds hacky. What's your actual requirement? The way you suggested sounds OK. You can go ahead with that implementation since from a performance standpoint, it doesn't take any extra over head. Just make sure you write a neat API to fetch data from your xml.

Community
  • 1
  • 1
Henry
  • 17,490
  • 7
  • 63
  • 98