2015-07-03 122 views
0

偶爾我想用靜態項目填充列表,哪些/哪裏是存儲這些靜態項目的最佳方式?Android自定義XML對象

我通常使用XML資源像這樣的東西:

<string-array name="category_ids"> 
    <item>0</item> 
    <item>1</item> 
    <item>2</item> 
</string-array> 

<array name="category_titles"> 
    <item>@string/category_all</item> 
    <item>@string/category_new</item> 
    <item>@string/category_hot</item> 
</array> 

<array name="category_icon_ids"> 
    <item>@null</item> 
    <item>@drawable/ic_category_star</item> 
    <item>@drawable/ic_category_thumb</item> 
</array> 

我訪問這些陣列和填充自定義對象的適配器。但是每次使用它都會讓我很煩惱。例如,當我更改列表中的順序時,我必須更改xml中的每個數組。

有沒有更好的解決方案?是否支持自定義XML對象?

回答

2

有時,使用可變化的自定義對象時,使用適配器訪問和填充這些項目會非常緊張。

相反,您可以使用json來處理比簡單數組更復雜的對象。

這裏是一個JSON實現的例子:

/res/raw文件夾:在你的類

加載數據:

InputStream jsonStream = context.getResources().openRawResource(R.raw.countries); 
JSONObject jsonObject = new JSONObject(Strings.convertStreamToString(jsonStream)); 
JSONArray jsonContries = jsonObject.getJSONArray("countries"); 
List<CountryVO> countries = new ArrayList<CountryVO>(); 
for (int i = 0, m = countries.length(); i < m; i++) { 
    JSONObject jsonCountry = countries.getJSONObject(i); 
    CountryVO country = new CountryVO(); 
    country.setCountryName(jsonCountry.getString("country")); 
    String co = jsonCountry.getString("countryCode"); 
    country.setCountryCode(co); 
    try { 
     Class<?> drawableClass = com.example.R.drawable.class; // replace package 
     Field drawableField = drawableClass.getField(co); 
     int drawableId = (Integer)drawableField.get(null); 
     Drawable drawable = getResources().getDrawable(drawableId); 
     country.setCountryFlag(drawable); 
    } catch (Exception e) { 
     // report exception 
    } 
    countries.add(country); 
} 

如果你不想做手動解析可以使用gson來傳遞對象並加載繪圖。

來源:https://stackoverflow.com/a/9809772/1549700

2

是的,你可以有你的自定義xmlres/xml/下保存,但在這種情況下,訪問內容是不完全免費。您可以使用getResources().getXml(R.xml.name_of_file)來檢索XmlResourceParser的實例,您必須使用該實例來解析xml