使用color.xml(一个字符串数组)设置颜色



嘿,我有这个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数组?

问题是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]);
        }  

我将使用2个数组,一个字符串数组用于名称,另一个int数组用于颜色值。

好的,我用另一种方法解决了。

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;
}

最新更新