我有一个从字符串数组资源填充的 ListView。我试图找出如何使用键值类型的结构,以便键显示在 ListView 中,并且当选择一行时我可以获得值。
我知道我可以为值维护一个单独的数组并使用行的选定索引进行查找,但这很难维护。
此外,我认为我可以制作一个 POJO 并使用我自己的自定义列表适配器使用这些对象构建列表,但如果可能的话,我只想使用一个简单的 xml 文件。
我正在阅读文档以查看是否可以在 xml 中执行此操作,但我还没有找到类似的东西?
谢谢你的时间。
最佳答案
您可能想要使用订购的 map ,例如 TreeMap或 LinkedHashMap并将其传递给您的适配器。
这将实现您想要实现的目标。
您基本上需要有一个适配器,它利用键值对数据结构(Map)并将其设置在您的 ListView 中,例如:
public class OrderedMapAdapter extends BaseAdapter {
Map.Entry[] entries;
/***
* Pass the key value pair map using an ordered map data structure
* @param orderedMap An ordered map, either LinkedHashMap or TreeMap
*/
public OrderedMapAdapter(LinkedHashMap orderedMap) {
this.entries = orderedMap.entrySet().toArray(new Map.Entry[0]);
}
public int getCount() {
return entries.length;
}
/***
* This should get you the position you want in Key-value pair format
* that you could use whenever the row is selected
*/
public Map.Entry getItem(int position) {
return entries[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// display your view here
return null;
}
}
关于Android ListView 使用key-value map 类型结构可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7163799/