将颜色的xml整数数组转换为字符串数组将返回空值-如何以编程方式将其转换为十六进制?

z0qdvdin  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(297)

我正在尝试从我的 colors.xml 到java String Array ```
#EA0027
#FF8717
#94E044
#0DD3BB
#24A0ED
#FF66AC
#DDBD37
#A5A4A4
#222222

<integer-array name="redditColors">
    <item>@color/redditred</item>
    <item>@color/redditorange</item>
    <item>@color/redditlime</item>
    <item>@color/redditmint</item>
    <item>@color/redditblue</item>
    <item>@color/redditpink</item>
    <item>@color/redditgold</item>
    <item>@color/redditgrey</item>
    <item>@color/redditsemiblack</item>
</integer-array>
我试过用 `getResources` 然后得到 `array` 并打印它。它返回 `length` 如预期的17个。但是当我使用 `Arrays.toString()` ,它给我一个空值数组。我做错了什么,如何让我的代码打印十六进制颜色?如: `[#EA0027, #FF8717, #94E044, ...... ]` ```
String[] colors = getResources().getStringArray(R.array.redditColors);
Log.d(TAG, "onCreate: " + colors.length);
Log.d(TAG, "onCreate: " + Arrays.toString(colors));

输出:

onCreate: 17
onCreate: [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]

编辑:

String[] colors = getResources().getStringArray(R.array.redditColors);
for(int i = 0; i < colors.length; i++){
   String hexInString = String.format("#%06X", (0xFFFFFF & colors[i]));
   Log.d(TAG, "onCreate: hex: " + hexInString);
}
eqzww0vc

eqzww0vc1#

颜色十六进制值不是字符串。所以像#ffffff这样的东西不能转换成字符串“#fffff”。
要获得所需的数组,可以遍历 colors 数组并使用以下代码将每个颜色十六进制转换为字符串,然后将其存储在新数组中。

String hexInString = String.format("#%06X", (0xFFFFFF & intColor));
eanckbw9

eanckbw92#

你应该使用 getIntArray() 而不是 getStringArray() 并转换为 HexInteger.toHexString() ```
int[] colors = getResources().getIntArray(R.array.redditColors);

for (int color : colors) {
String ColorString = "#" + Integer.toHexString(color);
Log.d("LOG_TAG", "Hex Color: " + ColorString);
}

结果:

2021-01-04 08:22:11.819 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ffea0027
2021-01-04 08:22:11.819 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ffff8717
2021-01-04 08:22:11.820 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ff94e044
2021-01-04 08:22:11.820 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ff0dd3bb
2021-01-04 08:22:11.820 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ff24a0ed
2021-01-04 08:22:11.820 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ffff66ac
2021-01-04 08:22:11.820 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ffddbd37
2021-01-04 08:22:11.820 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ffa5a4a4
2021-01-04 08:22:11.820 32308-32308/com.example.... D/LOG_TAG: Hex Color: #ff222222

相关问题