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);