使用ExpandableListView——当有Group选项展开时,怎么正确获取长按的Group选项

使用ExpandableListView——当有Group选项展开时,如何正确获取长按的Group选项。

当我们使用ExpandableListView时,实现点击一个GroupView则展开ChidView,那么这个时候,Adapter的大小前后是有变化的。

例如:假设有20个GroupView,每个GroupView都有一个ChildView。当全部GroupView都没有被展开的时候,Adapter的size是20;而当我们展开一个GroupView,显示出一个ChildView的时候,Adapter的size就增加了1。这个必须了解的。

当我们需要添加长按每一个GroupView的时候,获取当前被长按的GroupView的对象时,使用以下方法会出现如下问题。

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.booklist_context, menu);

		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
		
		// 获取当前长按项的下标
		final int index = ExpandableListView
				.getPackedPositionGroup(info.packedPosition.);
		//System.out.println("index----------->" + index);
		//System.out.println("Adapter的size------------->" +  expListView.getAdapter().getCount());
		mBookInfo = (BookInfoDTO) expListView.getAdapter().getitem(index);
	}

1、当所有的GroupView都没有展开的时候,能够正确获取每个GroupView的下标,通过Adapter就能得到绑定到这个GroupView中的对象。

2,、但,当有的GroupView被展开的时候,就不能使用上面的方法获取绑定在GroupView中的对象了。原因上面已经给出,因为此时的Adapter的size已经被改变。而此时获取的下标是20个GroupView的相对下标。跟Adapter中的下标所对应的对象并不一致,因为Adapter中还包含了被展开的ChildView。


使用以下的方法可以解决上面遇到的问题。

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.booklist_context, menu);

		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
		View vin = (View)info.targetView;
		mBookInfo = (BookInfoDTO)vin.getTag();

	}

在设配器中,为每一个GroupView set 一个Tag,也就是我们需要长按时候提出的对象。

这样我们就可以在以上的方法中取出每个GroupView中 的Tag,也就是我们绑定到GroupView中的对象。

这样就不用依赖于变化的Index。