3

我们可以像这里提到的那样从 android 中的 xml 文件中读取字符串数组。但这只能读取简单的字符串数组。

我的问题是我们可以读取包含其他类型对象的数组吗?xml文件是这样的:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array
        name="difficulty_level_names">
        <item>
            <name>IELTS</name>
            <type>1</type>
        </item>

        <item>
            <name>SAT</name>
            <type>2</type>
        </item>

        ................
        .........

    </string-array>
</resources>

更新:当然,每个项目中可以有更多参数..

4

1 回答 1

2

不,按照您提供的方式。我有两个解决方案,但都不理想。

1.

您可以创建多个数组,例如用于名称的字符串数组、用于整数的整数数组等。每个对象都将存储在这些数组中的相同索引处。维护起来并不简单,但在仅从对象访问一个属性的情况下,它可能会更节省内存。
我在:https ://stackoverflow.com/a/6774856/538169

或者

2.

您可以创建一个类型化数组并在数组中包含对象的属性。您可以通过以下方式翻译索引来访问该属性:

final int PROPERTIES_COUNT_IN_OBJECT = 2;
int objectIndex   = 0; // the first element in your's example
int propertyIndex = 1; // the second property: <type>1</type>
int indexInArray  = objectIndex * PROPERTIES_COUNT_IN_OBJECT + propertyIndex;

然后从 TypedArray 中获取这个属性。

第二种解决方案维护起来要糟糕得多。添加另一个属性将是一场噩梦。

于 2012-02-06T12:03:42.273 回答