Android的适配器视图点击监听器参数 - 位置和放大器; ID监听器、放大器、适配器、视图

2023-09-06 21:49:23 作者:上线只为等你

我设置的一个ListView长时间点击听众,我想用单击项目的索引来检索相应的对象。

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.

根据方法的签名和参数定义 Android的文档

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

我的问题是将位置和ID始终是相同的?这些定义似乎可以互换的,所以有什么区别?

My question is will "position" and "id" always be the same? Those definitions seem interchangeable, so what's the difference?

推荐答案

位置和ID可以是相同的,但它实际上取决于你所使用的适配器。

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

基本上2种方法中的适配器决定什么样的ID是 - 在的 SimpleCursorAdapter (和快速浏览一下源$ C ​​$ C)是从创建光标查询的_id字段,但在规定的id参数的适配器的方法是:

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)它允许适配器从位置转换为一个id为对象,和的 Adapter.hasStableIds()允许的ListView(或任何使用适配器缓存它) - 尽管你可能忽略hasStableIds()

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().

该ID将 Adapter.getItemId的返回值(INT)因此,如果您使用ArrayAdapter这将是一样的位置 - 快速搜索ArrayAdapter源$ C ​​$ C表明它使用返回位置; 摸出ID:)

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.