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

前端 未结 4 929
野的像风
野的像风 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:36

    My solution was instead of getting the position in the list and then using that to get the object from the ListArray or Hash, to just get the object in that position in the adapter and then retrieving whatever custom parameter or method from it that I needed. It's kind of obvious now but wasn't making sense at first.

    UPDATE It's a long bit of code so I will just give an overview:

    Instead of passing in a String for the list item, pass in a custom object. Lets say this object has two different values it stores. A name (retrievable by public method getName()) and an ID (retrievable by getId()).

    You have to override the getView() method for the adapter class and make it use the getName() method of the object and use that text to display in the list item.

    Then, when the item is clicked, just get the object from the adapter at that position and then get the ID:

    int id = adapter.get(position).getId();
    // Then do something with the ID, pass it to an activity/intent or whatever.
    

    Also I ditched the SeparatedListViewAdapter in favor of this. Much better and more flexible imo.

提交回复
热议问题