我的strings.xml文件中有一个标题数组。我想将这些标题从XML文件添加到Activity中的ListView中。我怎样才能做到这一点?请帮我举个例子。
答案 0 :(得分:0)
您可以做的是将XML解析为ArrayList,然后将ArrayList应用于ListView适配器。可能会像这样工作:
// create an arraylist object to add all the string values from the xml
ArrayList titles = new ArrayList();
// populate your array
XMLEncoder xmlEncoder = new XMLEncoder(BufferedOutputStream(
new FileOutputStream("titles.xml")));
xmlEncoder.writeObject(titles);
xmlEncoder.close();
// create another arraylist that will get applied to list view
ArrayList filteredTitles = new ArrayList();
// sort through all the xml strings in the first xml arraylist
// make sure were only getting the title nodes and adding them
// to the new arraylist 'filteredTitles'
foreach(string node in titles) {
if (node == titleNode) {
filteredTitles.add(node)
}
}
// apply the filtered titles to the arraylist
listView = (ListView) findViewById(R.id.your_list_view_id);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
filteredTitles );
listView.setAdapter(arrayAdapter);
答案 1 :(得分:0)
您可以按照以下方式进行操作:
在“活动”课程中,
private String[] items;
在onCreate()
方法内,初始化items数组:
items = getResources().getStringArray(R.array.<your-string-array-name>);
然后将此项目数组与适配器一起使用。