嘿,我得到了这个xml数组:
<resources>
<string-array name="colors">
<item>BLUE</item>
<item>CYAN</item>
<item>DARK_GRAY</item>
<item>GRAY</item>
<item>GREEN</item>
<item>LIGHT_GRAY</item>
<item>MAGENTA</item>
<item>ORANGE</item>
<item>PINK</item>
<item>RED</item>
<item>YELLOW</item>
<item>WHITE</item>
</string-array>
</resources>
我正在尝试这种简单的方法,显然无法正常工作:
public int[] getColorsArray(int i) {
int[] allColors = MyApplication.getContext().getResources().getIntArray(R.array.colors); //this is probably wrong
int[] array = new int[i];
for (int j = 0; j < array.length; j++) {
array[j] = allColors[j]; //this is wrong
}
return array;
}
}
有没有办法使用这样的xml数组?
答案 0 :(得分:1)
问题在于in xml you have defined string-array but in program you are trying to get int-array
。使用getStringArray
并检查结果
String[] allColors = getResources().getStringArray(R.array.colors); //this is probably wrong
String[] array = new String[allColors.length];
for (int j = 0; j < allColors.length; j++) {
array[j] = allColors[j]; //this is wrong
System.out.println(j+"...j..."+allColors[j]);
}
答案 1 :(得分:0)
我会使用2个数组,一个字符串数组用于名称,一个int数组用于颜色值。
答案 2 :(得分:0)
好的,我用另一种方式解决了这个问题。
private int[][] allColors() {
int rgbArray[][] = {
{3,48,208}, //blue
{73,33,65}, //blue
{63,92,202}, //blue
{107,134,233} //blue (yea, they are all different but I'm no woman)
};
return rgbArray;
}
public int[] getColorsArray(int i) {
int[][] allColors = allColors();
int[] array = new int[i];
for (int j = 0; j < array.length; j++) {
array[j] = Color.rgb(allColors[j][0], allColors[j][1], allColors[j][2]);
}
return array;
}