在 ListView 中添加来自 XML 资源文件的项目
Adding items from XML resource file in ListView
我的 strings.xml 文件中有一系列标题。我想将 XML 文件中的这些标题添加到我的 Activity 中的 ListView。我怎样才能做到这一点?请帮我举个例子。
您可以将 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);
您可以这样做:
在你的 Activity class,
private String[] items;
并在 onCreate()
方法中,初始化项目数组:
items = getResources().getStringArray(R.array.<your-string-array-name>);
并将此项目数组与您的适配器一起使用。
我的 strings.xml 文件中有一系列标题。我想将 XML 文件中的这些标题添加到我的 Activity 中的 ListView。我怎样才能做到这一点?请帮我举个例子。
您可以将 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);
您可以这样做:
在你的 Activity class,
private String[] items;
并在 onCreate()
方法中,初始化项目数组:
items = getResources().getStringArray(R.array.<your-string-array-name>);
并将此项目数组与您的适配器一起使用。