2

我的 colors.xml 中有一个颜色列表,它们的名称都采用 tColor1、tColor2、tColor3 等格式,我想在 for-to-do 循环中使用循环整数作为名称的一部分来检索它们。所以我有

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

现在我明白了我不能像那样使用 R 类,但是我还能用什么其他方法来获取颜色呢?

4

2 回答 2

6

你可以做这样的事情,假设你的newColorsArray 是一个int带有资源 id 的 Array?

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

getResources().getColor(...)如果它是您在该结果上使用的颜色数组:

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);
}
于 2012-06-09T19:40:46.757 回答
0

可以尝试

请参阅页面最后的 Typed Array .....

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

于 2012-06-09T19:46:13.197 回答