简体   繁体   English

将XML文件中的值转换为数组

[英]Getting values from an XML file into an array

In my app I use an array of drawable ids. 在我的应用程序中,我使用了一系列可绘制的ID。 It's an XML file saved at res/values/arrays.xml: 它是一个保存在res / values / arrays.xml的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </array>
</resources>

Then I retrive it using this code: 然后我使用以下代码检索它:

Resources res = getResources();
TypedArray icons = res.obtainTypedArray(R.array.icons);
Drawable drawable = icons.getDrawable(0);

But I get an error saying: array "cannot be resolved or is not a field". 但我得到一个错误说: 数组 “无法解析或不是字段”。

So How do I get an array of ints that contains the ids from the xml file? 那么如何获取包含xml文件中的id的整数数组?

Thanks :) 谢谢 :)

Try cleaning your project. 尝试清理您的项目。 Project - Clean... And check your imports. 项目 - 清洁......并检查您的进口。 Do CTRL + Shift + O CTRL + Shift + O.

You should use a typed array in arrays.xml file within your res folder that looks like this: 您应该在res文件夹中的arrays.xml文件中使用类型化的数组 ,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </string-array>

</resources>

Then in your activity access them like so: 然后在您的活动中访问它们,如下所示:

TypedArray imgs = getResources().obtainTypedArray(R.array.icons);
//get resourceid by index
imgs.getResourceId(i, -1)
// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, -1));

im wondering maybe should you have it declared in res/values/strings.xml like 我想知道也许你应该在res / values / strings.xml中声明它

<string-array name="numbers_array">
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
</string-array>

and then sunstitute your ids for the numbers in the array above... 然后为上面数组中的数字设置你的id ...

My code was ok. 我的代码还可以。 In my res dir there was an image with a capital letter in it's name! 在我的res目录中,有一个带有大写字母的图像! and that's Invalid file name which must contain only [a-z0-9_.] :) So that's why there was an error in the R class. 这是无效的文件名,必须只包含[a-z0-9_。] :)这就是R类中出现错误的原因。 Thanks you guys! 谢谢你们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM