当我在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,AdapterView
s use this to pass the exact item position within the adapter that initiated the context menu.