ExpandableListView及其子项显示上下文菜单

1.编写上下文菜单的xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    
<item
     android:id="@+id/deletehistorybutton"
     android:title="删除历史记录">       
</item>
<item
     android:id="@+id/deletehistorybutton2"
     android:title="删除历史记录2">       
</item>  

</menu>


 

2.生成上下文菜单

@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Sample menu");
		
		//显示 选中项目的group child 即使选中子项也是-1 group正常
		ExpandableListView.ExpandableListContextMenuInfo info
		= (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;		
		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        int group = ExpandableListView.getPackedPositionGroup(info.packedPosition);
        int child = ExpandableListView.getPackedPositionChild(info.packedPosition);
        Log.d("onCreateContextMenu","type:"+type+"group:"+group+"child:"+child); 
        
		getMenuInflater().inflate(R.menu.options, menu);绑定菜单xml
	}	


 

3.响应上下文菜单

@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onContextItemSelected(item);
		switch(item.getItemId())
		{
		case R.id.deletehistorybutton:
			Toast.makeText(mContext, "delete",Toast.LENGTH_SHORT).show();
			break;
		case R.id.deletehistorybutton2:
			Toast.makeText(mContext, "delete2",Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}


 

4.长按监听并显示菜单

expandableListView.setOnItemLongClickListener(new OnItemLongClickListener()
		{
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View childView,
					int flatPos, long id) {
				// TODO Auto-generated method stub				
				Log.d("LongClick", "start"); 
				if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD)
				{
				long packedPos = ((ExpandableListView)parent).getExpandableListPosition(flatPos);
				int groupPosition = ExpandableListView.getPackedPositionGroup(packedPos);
				int childPosition = ExpandableListView.getPackedPositionChild(packedPos);              
				Log.d("LongClick", "get position");
				
			 	expandableListView.showContextMenu();   ///子项显示菜单
			 	
			 	Log.d("LongClick","groupPosition:"+groupPosition+"childPosition:"+childPosition);				
				return true;
				}							
				return false;
			}			
		});


 

5注册菜单

registerForContextMenu(expandableListView);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值