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

二次信任 提交于 2019-12-08 01:34:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!