2012-07-07 56 views
16

假設我已經在android資源中存儲了一個2維數組,如下所示。我怎樣才能讓他們像Arraylist這樣的java集合?如何從Android的xml字符串資源檢索二維數組?

<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個維陣列,我們可以做到這一點的情況下,使用

getResources().getStringArray(R.array.countries_array); 

當countries_array就像

<resources> 
<string-array name="countries_array"> 
    <item>Bahrain</item> 
    <item>Bangladesh</item> 
    <item>India</item> 
</string-array> 
</resources> 

回答

36

只能用於一個資源文件的<string-array>元件對於單維數組。換句話說,<item></item>之間的所有內容都被認爲是單個字符串。

如果你想存儲在你描述(有效僞XML)數據的方式,你需要使用getStringArray(...)獲得項目作爲單個String[]和自己解析<name><codes>元素。

個人而言,我想可能與反限制的格式,如去...

<item>Bahrain,12345</item> 

...那麼就使用split(...)

另外,定義每個<item>作爲一個JSONObject如...

<item>{"name":"Bahrain","code":"12345"}</item> 
+0

很好的回答。但是有一件重要的事情是,如果json中有一個空格,用特殊字符替換''''是非常重要的,例如'{「title」:「WHOLED   SHOW」}''。否則什麼都不會顯示。它更多的是JSON的功能 – 2016-02-08 12:14:29

5

而是多值項,我wrote about another方法,您可以存儲您的複雜的對象作爲一個數組,然後用後綴名一個增量整數。循環遍歷它們,並根據需要從那裏創建一個強類型對象列表。

<resources> 
    <array name="categories_0"> 
     <item>1</item> 
     <item>Food</item> 
    </array> 
    <array name="categories_1"> 
     <item>2</item> 
     <item>Health</item> 
    </array> 
    <array name="categories_2"> 
     <item>3</item> 
     <item>Garden</item> 
    </array> 
<resources> 

然後您可以創建一個靜態方法來檢索它們:

public class ResourceHelper { 

    public static List<TypedArray> getMultiTypedArray(Context context, String key) { 
     List<TypedArray> array = new ArrayList<>(); 

     try { 
      Class<R.array> res = R.array.class; 
      Field field; 
      int counter = 0; 

      do { 
       field = res.getField(key + "_" + counter); 
       array.add(context.getResources().obtainTypedArray(field.getInt(null))); 
       counter++; 
      } while (field != null); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      return array; 
     } 
    } 
} 

,它可以像現在這樣消耗:

for (TypedArray item : ResourceHelper.getMultiTypedArray(this, "categories")) { 
    Category category = new Category(); 
    category.ID = item.getInt(0, 0); 
    category.title = item.getString(1); 
    mCategories.add(category); 
} 
+0

for循環在getString行引發錯誤。預期資源類型styleable。 – Nilpo 2016-04-19 08:20:13

+0

@Nilpo向封裝方法或類添加'@SuppressWarnings(「ResourceType」)'解決了這個問題。 (這可能只發生在新版Android Studio中。) – Nilpo 2016-04-19 08:27:42