获取所选项目的位置...?

3

我是一个新手,正在学习Android开发。以下是一段代码:

protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Note selectedName = adapter.getItem(position);
adapter.removeItem(selectedName);

如您所见,位置表示所选项目的位置。这很好。但我更喜欢长按:

public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.ctxmemu_delete:
** I need to use POSITION mentioned above! **

但是在这种方法中,getSelectedItemPosition返回位置-9995845834585(或类似的内容)。或者它会出现错误(无法将光标移到位置 - 我在我的应用程序中使用SQL)

如何正确地从列表中获取位置? 附言:对我的糟糕英语感到抱歉 :(

更新: 我已经将此添加到我的SQL适配器中:

public int getPosition(){
return cursor.getPosition();    }

并修改为:

case R.id.ctxmemu_delete:
int position = adapter.getPosition();
Note seln = adapter.getItem(position);
adapter.removeItem(seln);
return true;

现在它能够工作……但我认为它非常丑陋。


1
为什么不使用onListItemLongClick监听器,而要使用上下文菜单呢? - Swayam
Kondra,请检查我的答案 :) 它应该解决你的问题。 - Simon Dorociak
我现在正在努力理解它。 - Groosha
3个回答

1
你只需要使用onListItemLongClick()而不是onListItemClick()。

我需要继承超类吗?(或类似的东西) - Groosha

1
为什么不使用onListItemLongClick监听器而不是使用上下文菜单?
protected void onListItemLongClick(ListView l, View v, int position, long id) {
super.onListItemLongClick(l, v, position, id);
Note selectedName = adapter.getItem(position);
adapter.removeItem(selectedName);
}

我想制作我的上下文菜单(将来) - Groosha

1
public boolean onContextItemSelected(MenuItem item) { ... }

由于您正在使用ContextMenu,因此与ItemClickListener有些不同

您可以使用MenuInfo来获取在ListView中的位置

AdapterView.AdapterContextMenuInfo info = 
                         (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

该属性为int类型,名称为info.position,返回上下文菜单在适配器中显示的位置。

注意: 您还可以查看类似的OnItemLongClickListener


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接