当我在onContextItemSelected方法中,想要通过listview的getSelectedItemPosition()方法来获得当前选中的position时,无论点击的是哪个选项,返回的值都是-1.
后来又换了一种方法,通过监听listview的OnItemLongClickListener接口来实现,但是还是不行。
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int position, long second) {
selectedPosition = position;
return true;
}
原因是当你启用OnItemLongClickListener接口时,onContextItemSelected方法便不会再被触发了。
没办法,只能google之。从搜索结果看,网上还是有不少人有这个问题的,其实解决方法很简单,只需要在onContextItemSelected中添加下面两行代码:
AdapterContextMenuInfo info=(AdapterContextMenuInfo)item.getMenuInfo();
int index=info.position;
AdapterContextMenuInfo用于onCreateContextMenu的回调,关于ContextMenu,官网是这样描述的:
Additional information regarding the creation of the context menu. For example,AdapterViews use this to pass the exact item position within the adapter that initiated the context menu.
本文探讨了在Android开发中使用ListView的onContextItemSelected方法时遇到的问题,即无法正确获取选中项的位置。通过使用AdapterContextMenuInfo实现了对选中位置的准确获取。
937

被折叠的 条评论
为什么被折叠?



