【问题标题】:ExpandableListAdapter add/delete groupExpandableListAdapter 添加/删除组
【发布时间】:2011-10-02 03:25:00
【问题描述】:

我需要能够在我的 expandableListAdapter 中动态创建和删除组。我已经浏览了所有我能找到的东西并且被卡住了。我不需要特定的代码,只是为了指出正确的方向。

【问题讨论】:

    标签: android expandablelistadapter


    【解决方案1】:

    首先,我们需要一些数据结构(保留对它们的引用以供以后使用)。

    headerData = new ArrayList<HashMap<String, String>>();
    childData = new ArrayList<ArrayList<HashMap<String, Object>>>();
    

    headerData 是组列表 - 使用 HashMap 是因为每个组可以有多个显示值,每个显示值都通过键映射到布局上。

    childData 是属于每个组的项目列表。它是一个列表列表,每个列表都包含 HashMaps - 类似于组,每个孩子可以有多个通过键映射的显示值。

    我们在创建时将这些数据结构提供给 ExpandableListAdapter。我们还告诉适配器应该如何映射显示值;在此示例中,组和子项都有两个显示值,键“name”和“fields”,它们映射到提供的布局中的 text1 和 text2。

    adapter = new SimpleExpandableListAdapter( SearchLogs.this, 
            headerData, R.layout.customlayout_group,
            new String[] { "name", "fields" }, new int[] { R.id.text1, R.id.text2 }, 
            childData, R.layout.customlayout_child, 
        new String[] { "name", "fields" }, new int[] { R.id.text1, R.id.text2 } );
    setListAdapter(adapter);   // assuming you are using ExpandableListActivity
    

    到目前为止,我们有一个空的 ExpandableList。我们可以通过创建 HashMap 来动态填充它(例如使用 AsyncTask),该 HashMap 为我们正在使用的键提供值,然后将它们添加到我们的列表中。

    例如,要添加一个有几个孩子的组,我们可以...

    HashMap<String, String> group = new HashMap<String, String>();
    group.put("name", "whatever...");
    group.put("fields", "...");
    
    ArrayList<HashMap<String, Object>> groupChildren = new ArrayList<HashMap<String, Object>>();
    
    HashMap<String, Object> child1 = new HashMap<String, Object>();
    child1.put("name", "child name");
    child1.put("fields", "...");
    
    HashMap<String, Object> child2 = new HashMap<String, Object>();
    child2.put("name", "another child");
    
    groupChildren.add(child1);
    groupChildren.add(child2);
    
    headerData.add(group);
    childData.add(groupChildren);
    

    headerData 中的每个 HashMap 对应(按顺序)childData 中的一个 ArrayList,其中包含定义实际子项的附加 HashMap。所以即使你要添加一个空组,也要记得给 childData 添加一个对应的(空的)ArrayList。

    我们刚刚在列表末尾添加了一个组 - 只要我们注意插入到 headerData 和 childData 中的相同位置,我们就可以轻松插入。删除组是一样的 - 一定要从 headerData 和 childData 的相同位置删除。

    最后通知适配器数据发生了变化,这会导致List刷新。如果使用 AsyncTask,这必须在 doInBackground 之外完成(在这种情况下使用 onProgressUpdate)。

    adapter.notifyDataSetChanged();
    

    我希望这可以帮助您朝着正确的方向前进。 ExpandableList,就数据的存储方式而言,绝对是比较复杂的Android视图之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 2021-03-14
      • 2016-03-09
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多