Brian Ecker
Brian Ecker

Reputation: 2077

Retrieve a color from values/colors.xml using a variable in name (R.color.name + variable)

I have a list of colors in my colors.xml that all have names in the format tColor1, tColor2, tColor3, etc. and I want to retrieve them in a for-to-do loop using the looping integer as part of the name. So I have

for (int i = 0; i < numTrails; i++) {
    newColors[i] = R.color.tColor + i;
}

Now I understand that I can't use the R class like that, but what other method can I use to get the colors?

Upvotes: 2

Views: 4660

Answers (2)

Dheeresh Singh
Dheeresh Singh

Reputation: 15701

can try

refer Typed Array at the last of the page .....

http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray

Upvotes: 0

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

You can do something like this, assuming your newColors Array is an int Array with the resource ids?

String colorId = "tColor";
Resources resources = getResources();
for (int i = 0; i < numTrails; i++) {
    newColors[i] = resources.getIdentifier(colorId+i, "color", getPackageName());    
}

If it is an array of your colors use getResources().getColor(...) on that result instead:

String colorId = "tColor";
Resources resources = getResources();
for (int i = 0; i < numTrails; i++) {
    int resId = resources.getIdentifier(colorId+i, "color", getPackageName());
    newColors[i] = resources.getColor(resId);
}

Upvotes: 6

Related Questions