需要帮助才能理解onChildClick android

时间:2011-02-14 21:06:13

标签: android

您好我已成功通过示例在我的应用程序中创建可扩展列表视图并且非常困难,但我真的不明白我是如何成功获得用户点击的正确索引,我的意思是,我并不是真的知道childData中的内容以及groupData和childData如何相互关联。我需要一些帮助来理解这些人,我从未见过这样的仿制药。所以这是我的问题:

1- childData和groupData如何相互关联,groupData是否为childData Map? 2-如何String selectedWord = childData.get(groupPosition).get(childPosition).get(NAME);    在listView中获得正确的单词和标题(或组)?

以下是代码:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.expandable_list_layout);

        DBManager db = new DBManager(getApplicationContext());

        List<String> header = db.selectAllCategories();
        List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
        final List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();

        for (String category : header) {
            Map<String, String> curGroupMap = new HashMap<String, String>();
            groupData.add(curGroupMap);
            curGroupMap.put(NAME, category);
            List<String> categoryWords = db.selectWordsFromCategory(category);

            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
            for (String word : categoryWords) {
                Map<String, String> curChildMap = new HashMap<String, String>();
                children.add(curChildMap);

                curChildMap.put(NAME, word);
            }
            childData.add(children);
        }

        //create SimpleExpandableListAdapter object...

        lv.setOnChildClickListener(new OnChildClickListener() {

            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

//How does the below code works? 
//How can i get the group value from the childData map
//i thought childData had only childs in it?
                String selectedWord = childData.get(groupPosition).get(childPosition).get(NAME);

                Log.i("You clicked here:", selectedWord)
                return false;
            }
        });

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

groupDatachildData是两个不相关的数据结构。以下是JSONey表示法中的内容示例,以了解其中的内容:

groupData = [{"label": "Group 1" }, {"label" : "Group 2"}]
childData = [
  [{"label" : "Child 1.1"}, {"label" : "Child 1.2"}],
  [{"label" : "Child 2.1"}, {"label" : "Child 2.2"}, {"label" : "Child 2.3"}]
]

如果您的适配器查看这样的数据结构,您将获得具有两个组的可扩展列表视图,第一组中有两个子组,第二组中有三个子项。

childData中的索引对应于组,其内部列表中的索引对应于组内的子项。内部列表的元素是具有适配器将绑定到列表项中的文本视图的值的映射。

希望这有帮助!