【问题标题】:Adding items from XML resource file in ListView [closed]在 ListView 中从 XML 资源文件添加项目 [关闭]
【发布时间】:2018-12-05 12:58:10
【问题描述】:

我的 strings.xml 文件中有一组标题。我想将 XML 文件中的这些标题添加到我的 Activity 中的 ListView 中。我怎样才能做到这一点?请帮我举个例子。

【问题讨论】:

  • 这个问题可能会被搁置,因为您没有提供您的minimal reproducible example XML 文件,也没有提供您的预期结果的外观/行为方式。这里的反对票只是表明需要紧急关注。

标签: java android xml listview android-resources


【解决方案1】:

你可以这样做:

在您的 Activity 类中,

private String[] items;

onCreate()方法内部,初始化items数组:

items = getResources().getStringArray(R.array.<your-string-array-name>);

并将此 items 数组与您的适配器一起使用。

【讨论】:

    【解决方案2】:

    您可以将 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); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多