Android - SeparatedListAdapter - How to get accurate item position on onClick?

前端 未结 4 928
野的像风
野的像风 2021-01-13 06:09

I\'m using Sharkey\'s SeparatedListAdapter class in order to have a ListView that is separated by sections.

The class works great, but the problem I\'m having is in

4条回答
  •  悲哀的现实
    2021-01-13 06:37

    For anyone else I too recently ran into this problem and ended up here, I solved by:

    First altering the Map to take an 'id'

    public Map createItem(String title, String caption, String id) { 
      Map item = new HashMap(); 
      item.put(ITEM_TITLE, title); 
      item.put(ITEM_CAPTION, caption); 
      item.put("id", id); // Add a unique id to retrieve later
      return item;}
    

    Second when adding a section make sure to include an id:

     List> GeneralSection = new LinkedList>(); 
              GeneralSection.add(createItem(FirstName[GeneralInt] + " " + LastName[GeneralInt], Whatever[GeneralInt], UniqueId[GeneralInt]));   
    //Unique id could be populated anyway you like, database index 1,2,3,4.. for example like above question.
              adapter.addSection("GeneralSection ", new SimpleAdapter(getActivity(), GeneralSection , R.layout.list_complex, 
                new String[] { ITEM_TITLE, ITEM_CAPTION }, new int[] { R.id.list_complex_title, R.id.list_complex_caption }));
    

    Finally Use a Map in ItemClickListener to retrieve 'id' of the correct position:

      @Override
            public void onItemClick(AdapterView arg0,  View v, int position, long arg3) {
                // TODO Auto-generated method stub
    
                Map map = (Map) arg0.getItemAtPosition(position);
                String UniqueId = map.get("id");
                Log.i("Your Unique Id is", UniqueId); 
    //Can then use Uniqueid for whatever purpose
    //or any other mapped data for that matter..eg..String FirstName = map.get("ITEM_TITLE");
    
    
        }
    

    Hope this helps someone.

提交回复
热议问题