代码之家  ›  专栏  ›  技术社区  ›  Jan-Patrick Ahnen

带有xml字典的ListView适配器

  •  0
  • Jan-Patrick Ahnen  · 技术社区  · 14 年前

    我想为ListView设置一个适配器,其中ListView的项是Dictionary。 出于本地化目的,我更喜欢在“values”文件夹下用xml定义这些项。

    目前,我使用一个带有字符串的简单列表,其中数组在\values\arrays.xml中定义

    但我不想使用列表中所选项目的索引——如果我有时更改项目的顺序,我必须更改依赖于此隐式索引的所有代码。使用已定义的键会容易得多。

    我怎么能这么做?

    1 回复  |  直到 14 年前
        1
  •  0
  •   Michał Klimczak    14 年前

    我不会用字典。它是 obsolete .我认为你最好用 ArrayList 习惯的 Object s或a HashMap .那你就可以拿到这个了 对象 来自您的 Adapter 以下为:

    listview.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
                  //adapter.getItem(position); - this is how you can acces the object
                  //connected to the selected item from the list
                  //Then you can easily access an id of this object (or from HashMap)
    
                }
    });
    

    编辑:如果你想有一个xml列表,你可以随时向你的资源中添加一个抽象的xml文件。这些也可以本地化。它是这样的:

    <my_word>
        <id>123</id>
        <word>My word</word>
    </my_word>
    

    但它将涉及XML解析,所以不一定是更容易的解决方案。