2011-02-14 59 views
1

你好,我已經成功地在我的應用程序中做了一個可擴展的列表視圖,從一個例子和很多的鬥爭,但我真的不明白我是如何成功地得到用戶點擊正確的索引,我的意思,我真的不知道childData中的內容以及groupData和childData如何相互關聯。我需要一些幫助來理解這些人,我從來沒有以這種方式看過泛型。所以這裏是我的問題:需要幫助瞭解onChildClick android

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

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"}] 
] 

如果您的適配器看着這樣的數據結構,你會得到擴張的ListView有兩組,第一組的兩個孩子,三第二組兒童。

childData中的索引對應組,其內部列表中的索引對應子組內部的子索引。內部列表的元素是具有適配器將綁定到列表項中的文本視圖的值的映射。

希望這會有所幫助!