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

android, android-resources, colors

Solution

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);
}

Problem

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?

Original source