有时在使用可能会发生变化的自定义对象时,使用适配器访问和填充这些项目可能会非常有压力。
相反,您可以使用json 来处理比简单数组更复杂的对象。
这是一个 json 实现的示例:
在/res/raw 文件夹中:
{ "countries" : [
{"country" : "Albania", "countryCode" : "al" },
{"country" : "Algeria", "countryCode" : "dz"},
{"country" : "American Samoa", "countryCode" : "as"},
{"country" : "India", "countryCode" : "in"},
{"country" : "South Africa", "countryCode" : "sa"}
]}
在你的类中加载数据:
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