【问题标题】:Android Custom XML ObjectsAndroid 自定义 XML 对象
【发布时间】:2015-09-21 16:01:04
【问题描述】:

偶尔我想用静态项目填充一个列表,存储这些静态项目的最佳方式是什么/在哪里?

我通常使用这样的 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 对象?

【问题讨论】:

    标签: android xml list resources


    【解决方案1】:

    有时在使用可能会发生变化的自定义对象时,使用适配器访问和填充这些项目可能会非常有压力。

    相反,您可以使用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

    【讨论】:

      【解决方案2】:

      是的,您可以将自定义的xml 存储在res/xml/ 下,但在这种情况下访问内容并不是完全免费的。您可以使用getResources().getXml(R.xml.name_of_file) 来检索XmlResourceParser 的实例,您必须使用它来解析xml

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多