2015-07-03 89 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