问题
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?
回答1:
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);
}
回答2:
can try
refer Typed Array at the last of the page .....
http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray
来源:https://stackoverflow.com/questions/10963931/retrieve-a-color-from-values-colors-xml-using-a-variable-in-name-r-color-name