Android AdapterView Click Listener Parameters - position & id

后端 未结 2 1260
时光取名叫无心
时光取名叫无心 2021-01-15 16:54

I\'m setting a long click listener on a listview and I want to use the index of the clicked item to retrieve the corresponding object.

Method signature and paramete

相关标签:
2条回答
  • 2021-01-15 17:14

    ID is the id from the database (i.e. _ID). position is the position in the Array or ArrayList.

    For example: if you have in your DB records with IDs 1,2,3,4 and you use SQL to retrieve the records (and populate the array or ArrayList) you may have some filter (where clause) and show just elements with IDs 1 and 3. That way you have just 2 possible positions - 0 and 1.

    The difference is: you may think for row ID as some external ID, that belongs to data row itself. In contrary position "belongs" to the list view and it's adapter.

    0 讨论(0)
  • 2021-01-15 17:18

    Position and ID may be the same, but it really depends on the adapter you're using.

    Basically 2 methods in the adapter dictate what the ID will be - in the case of a SimpleCursorAdapter (and a quick look at the source code) it's the '_id' field from the query that created the cursor, but the methods in the Adapter that dictate the id parameter are:

    Adapter.getItemId(int) which allows the adapter to convert from position to an id for the object, and Adapter.hasStableIds() which allows the ListView (or anything using the Adapter to cache it) - although you can probably ignore hasStableIds().

    The id will be the returned value of Adapter.getItemId(int) so if you use an ArrayAdapter it will be the same as the position - a quick search of the ArrayAdapter source code shows it's using return position; to work out the id :)

    If you use a custom adapter, then it's completely up to you.

    0 讨论(0)
提交回复
热议问题