<resources>
<color name="red">#e51c23</color>
<color name="pink">#e91e63</color>
<color name="purple">#9c27b0</color>
<color name="deep_purple">#673ab7</color>
<string-array name="colors_hex_code">
<item>@color/red</item>
<item>@color/pink</item>
<item>@color/purple</item>
<item>@color/deep_purple</item>
</string-array>
</resources>
您好,我声明了colors.xml,就像代码一样,当我访问这个值时,表单就像
一样String[] s = getResources().getStringArray(R.array.colors_hex_code);
Toast.makeText(getActivity(), "First Color: " + s[0], Toast.LENGTH_SHORT).show();
,为什么s [index]总是返回null?我想从“colors_hex_code”字符串数组中获取十六进制颜色代码。可以像这样访问吗?请帮忙。谢谢你。
答案 0 :(得分:3)
将字符串数组更改为整数数组:
<resources>
<color name="red">#e51c23</color>
<color name="pink">#e91e63</color>
<color name="purple">#9c27b0</color>
<color name="deep_purple">#673ab7</color>
<integer-array name="colors_hex_code">
<item>@color/red</item>
<item>@color/pink</item>
<item>@color/purple</item>
<item>@color/deep_purple</item>
</integer-array>
</resources>
和java代码:
int[] s = getResources().getIntArray(R.array.colors_hex_code);
Toast.makeText(getActivity(), "First Color: " + String.format("#%06X", (0xFFFFFF & s[0])), Toast.LENGTH_SHORT).show();
答案 1 :(得分:2)
你可能不应该声明一个&#34;字符串数组&#34;如果你存储颜色而不是字符串。
试着看一下这篇文章:
How can I save colors in array.xml and get its back to Color[] array
答案 2 :(得分:0)
创建 colour.xml 文件
添加一些颜色:
<color name="white">#ffffff</color>
<color name="black">#000000</color>
然后在活动中:
textView.setTextColor(R.color.white);
答案 3 :(得分:0)
来自StringArray
<item> A string, which can include styling tags. The value can be a reference to another string resource
因此,如果您想拥有string-array
,则需要在strings.xml
中声明颜色,或者
答案 4 :(得分:0)
替换
<string-array name="colors_hex_code">
<item>@color/red</item>
<item>@color/pink</item>
<item>@color/purple</item>
<item>@color/deep_purple</item>
</string-array>
与
<string-array name="colors_hex_code">
<item>#FFEA4E3C</item>
<item>#FFF67A81</item>
<item>#FF665EC7</item>
<item>#FF3B3673</item>
</string-array>
答案 5 :(得分:0)
使用数组而不是字符串数组
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#e51c23</color>
<color name="pink">#e91e63</color>
<color name="purple">#9c27b0</color>
<color name="deep_purple">#673ab7</color>
<array name="colors_hex_code">
<item>@color/red</item>
<item>@color/pink</item>
<item>@color/purple</item>
<item>@color/deep_purple</item>
</array>
</resources>
使用
获取颜色int[] s = context.getResources().getIntArray(R.array.colors_hex_code);
// It will show you a color code value
Toast.makeText(getActivity(), "First Color: " + s[0], Toast.LENGTH_SHORT).show();