0

我正在构建一个包含列表的应用程序,列表中的每个项目都有一些值(名称、描述和日期)。我制作了一个 XML 文件,其中包含列表中任何项目的结构。
我还有另一个 XML 文件,其中包含列表中的项目(每个<item>标签都有<name><desc>子项<date>
问题是我不知道如何将所有内容放在正确的位置。我在网上搜索过它,我发现它叫XML Parsing,但是我找到的唯一教程就是这个,但是它写的不清楚所以我没有理解它..
有人可以解释一下或者给我一个很好的教程吗?

编辑:
这是结构 XML 文件
这是内容 XML 文件

4

2 回答 2

2

您设置为 a 的数据string-array未正确构建为显示在ListView. 它应该是这样的:

    <string-array name="exams">
        <item>@array/exam1</item>
        <item>@array/exam2</item>
        <item>@array/exam3</item>
        <item>@array/exam4</item>
    </string-array>
    <string-array name="exam1">
        <item>One</item>
        <item>11111111One</item>
        <item>25/7/12</item>
    </string-array>
    <string-array name="exam2">
        <item>Two</item>
        <item>2222222222Two</item>
        <item>28/7/12</item>
    </string-array>
    <string-array name="exam3">
        <item>Three</item>
        <item>333333333333Three</item>
        <item>29/1/10</item>
    </string-array>
    <string-array name="exam4">
        <item>Four</item>
        <item>444444444Four</item>
        <item>21/2/11</item>
    </string-array>

要在适合ListView您编写的数据结构中解析它(部分代码来自此答案:Android Resource - Array of Arrays):

 Resources res = getResources();
        ArrayList<Exam> extractedData = new ArrayList<Exam>();
        TypedArray ta = res.obtainTypedArray(R.array.exams);
        int n = ta.length();
        for (int i = 0; i < n; ++i) {
            int id = ta.getResourceId(i, 0);
            if (id > 0) {
                extractedData.add(new Exam(res.getStringArray(id)));
            } else {
                // something wrong with the XML, don't add anything
            }
        }
        ta.recycle();

该类Exam是一个简单的数据持有者类:

public class Exam {
    String name, desc, date;

    public Exam(String[] dataArray) {
        this.name = dataArray[0];
        this.desc = dataArray[1];
        this.date = dataArray[2];
    }
}

然后,您将extractedData ArrayList在自定义适配器中使用您的行布局:

public class CustomAdapter extends ArrayAdapter<Exam> {

    private LayoutInflater mInflater;

    public CustomAdapter(Context context, int textViewResourceId,
            List<Exam> objects) {
        super(context, textViewResourceId, objects);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(
                    R.layout.your_layout_file, parent, false);
        }
        Exam e = getItem(position);
        ((TextView) convertView.findViewById(R.id.name)).setText(e.name);
        ((TextView) convertView.findViewById(R.id.desc)).setText(e.desc);
        ((TextView) convertView.findViewById(R.id.date)).setText(e.date);
        return convertView;
    }

}
于 2012-07-29T12:21:31.093 回答
0

我最近通过遵循本教程学习了如何在 android 中解析 XML

http://developer.android.com/training/basics/network-ops/xml.html

希望能帮助到你 :)

于 2012-07-28T21:28:25.540 回答