问题
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 parameter definition according to android docs
public abstract boolean onItemLongClick (AdapterView<?> parent, View view, int position, long id)
Parameters
parent The AbsListView where the click happened
view The view within the AbsListView that was clicked
position The position of the view in the list
id The row id of the item that was clicked
My question is will "position" and "id" always be the same? Those definitions seem interchangeable, so what's the difference?
回答1:
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.
回答2:
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 position
s - 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.
来源:https://stackoverflow.com/questions/7859910/android-adapterview-click-listener-parameters-position-id