注册为ContextMenu的listView如何获得selectedItemPosition

当我在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.


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值