问题描述
假设我在android资源中存储了一个二维数组,如下所示。如何在像Arraylist这样的java集合中获取它们?
Suppose I have stored a 2 dimensional array in android resource as shown below. How can I get them in a java collection like Arraylist?
<resources>
<string-array name="countries_array">
<item>
<name>Bahrain</name>
<code>12345</code>
</item>
<item>
<name>Bangladesh</name>
<code>54545</code>
</item>
<item>
<name>India</name>
<code>54455</code>
</item>
</string-array>
</resources>
例如,对于1维数组,我们可以使用
For example in case of 1 dimensional array we can do it using
getResources().getStringArray(R.array.countries_array);
当countries_array像
When the countries_array is like
<resources>
<string-array name="countries_array">
<item>Bahrain</item>
<item>Bangladesh</item>
<item>India</item>
</string-array>
</resources>
推荐答案
< string- array>
资源文件的元素只能用于单维数组。换句话说,< item>
和< / item>
之间的所有内容都被视为单个字符串。
The <string-array>
element of a resources file can only be used for single dimension arrays. In other words, everything between <item>
and </item>
is considered to be a single string.
如果您想以您描述的方式存储数据(实际上是伪XML),您需要将这些项目作为单个 String []
使用 getStringArray(...)
并解析< name>
和你自己的< codes>
元素。
If you want to store data in the way you describe (effectively pseudo-XML), you'll need to get the items as a single String[]
using getStringArray(...)
and parse the <name>
and <codes>
elements yourself.
我个人可能会采用限定格式,例如: ...
Personally I'd possibly go with a de-limited format such as...
<item>Bahrain,12345</item>
...然后只需使用拆分(...)
。
...then just use split(...)
.
或者,将每个< item>
定义为JSONObject,例如...
Alternatively, define each <item>
as a JSONObject such as...
<item>{"name":"Bahrain","code":"12345"}</item>
这篇关于如何从Android的xml字符串资源中检索2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!