首页 > 解决方案 > 在 listView 中合并相同项目的最佳方法是什么?

问题描述

我有lisView一些可能具有相似属性的物品,我想要:

首先,找到这些具有相似属性的项目。

第二,将这些合并到列表视图的一个行项中,

最后,当项目被选中时,在展开的布局中显示它们的项目(合并的)。

我的想法不是那么强烈,我想使用for循环来找到相似的项目,然后将它们存储在 an 中array,最后adapter检查是否项目是合并的type然后使用Expandable Layout.

有更好的解决方案吗?

标签: androidalgorithmlistviewarraylist

解决方案


考虑使用 HashMap。

HashMap<String, ArrayList<Item>> map = new HashMap<String, ArrayList<Item>>();

您的属性是字符串或可以比较的任何内容,并且作为值,它将存储您的项目列表。为此,请使用以下内容:

for (int i = 0; i < listOfItems.size(); i++) {
        if(map.containsKey(listOfItems.get(i).property){
          map.get(listOfItems.get(i).property).add(listOfItems.get(i));
        }else{
          ArrayList temp = new ArrayList();
          temp.add(listOfItems.get(i);
          map.put(listOfItems.get(i).property, listOfItems.get(i))
       }
    }

并获取具有相同属性的对象列表,请使用

map.get(property)

推荐阅读