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 my onListItemClick()
handler. If I have the following sectioned list:
---------
| A |
---------
| Alex |
| Allan |
---------
| B |
---------
| Barry |
| Bart |
| Billy |
| Brian |
---------
| C |
---------
etc...
When you want to click on an item in the list, you get the position
of the item and then do something with it.
In my case, my list is a dynamic list of people's names. The names come from a database that is put into a List<CustomClass>
before going into list. It's important for me to know the position of the item that I click on because I use the item position
to determine other information about the person in the List object.
Now, the problem is this: When you click an item in the list, the headers count as items, even though they are unclickable. In the above example, the positions in the list are as follows
Alex = 1
Allan = 2
Barry = 4
Bart = 5
Billy = 6
Brian = 7
But in my original List
object the order is like so
Alex = 0
Allan = 1
Barry = 2
Bart = 3
Billy = 4
Brian = 5
So whenever I click on an item, like Alex, my code runs the onClick
handler, determines that Alex is at position 1
in the and then retrieves Allans info from the List
instead of Alex's.
Do you see the delima here? What is the approach I should take to this problem?
You could use setTag()
for your every item in the listView
. This can be done by adding this tag before you return the view from getView()
function in the listAdapter
. lets say your list adapter return convertView
,then in the list adapter.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null)
{
convertView = mLayoutInflater.inflate(R.layout.morestores_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// populate holder here, that is what you get in onItemClick.
holder.mNameofItem = "NameofaPerson";
return convertView;
}
static class ViewHolder {
TextView mName;
Button mAction;
ImageView mLogo;
// use this class to store the data you need, and use appropriate data types.
String mNameofItem.
}
when ever you get a click on the list item, use
public void onItemClick(AdapterView<?> arg0, View convertView, int arg2,
long arg3) {
ViewHolder holder = (ViewHolder) convertView.getTag();
// holder has what ever information you have passed.
String nameofItemClicked = holder.mNameofItem;
// access the information like this.
}
This approach doesn't need the position of the item in the list, just wanted to let you know different approach.
HTH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With