我正在构建一个包含列表的应用程序,列表中的每个项目都有一些值(名称,描述和日期)。我制作了一个XML文件,其中包含列表中任何项目的结构
我还有另一个XML文件,其中包含列表中的项目(每个<item>
标记都有<name>
,<desc>
和<date>
个孩子)
问题是我不知道如何将所有内容放在正确的位置..我在网上搜索过它,我发现它叫做XML解析,但我发现的唯一教程是this one,但它是写得不清楚所以我不理解..
有人可以解释一下或给我一个很好的教程吗?
答案 0 :(得分:2)
您设置为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;
}
}
答案 1 :(得分:0)
我最近学会了如何按照本教程
解析android中的XMLhttp://developer.android.com/training/basics/network-ops/xml.html
希望有所帮助:)