简体   繁体   中英

Is it possible to select a custom list view item with its list item id instead of list item position in android?

Is it possible to get the list item's id instead of getting the list item through its position? because the problem i face is: I use custom listview. I sort the list items on button click. After the list items are sorted in new order, if i click first item, the list item selected of the original item before sorting. also i use database to fetch the list item click. I match the database id with the list item position selected. How to solve it? any help is highly appreciated and thanks in advance...

I think your best approach here is to use the tag property and set it equal to whatever id you want to use on retrieval of data from your db:

view.setTag(myId);

Then when the view is clicked, inside your Listener you can simply retrieve the tag value instead of the position:

int id = view.getTag();

You may need to do some casting since Tag is of type object, but this will work for what you need. If you want to go further, I recommend using a Model class to hold the ID value, then you can simply set that object as the tag, and reference all properties of your model when you retrieve (not just the ID itself).

Hope this helps. Brian

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM