使用名称中的变量(R.color.name +变量)从values/colors.xml中检索颜色 [英] Retrieve a color from values/colors.xml using a variable in name (R.color.name + variable)
问题描述
我的colors.xml中有一个颜色列表,所有颜色名称的格式均为tColor1,tColor2,tColor3等.名字.所以我有
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;
}
现在,我知道我不能像这样使用R类,但是我可以使用什么其他方法来获得颜色?
Now I understand that I can't use the R class like that, but what other method can I use to get the colors?
推荐答案
您可以执行以下操作,假设您的newColors
数组是具有资源ID的int
数组?
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());
}
如果它是您的颜色数组,请在该结果上使用getResources().getColor(...)
:
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);
}
这篇关于使用名称中的变量(R.color.name +变量)从values/colors.xml中检索颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!