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

来源:互联网 发布:手机音频编辑软件中文 编辑:程序博客网 时间:2024/06/06 01:44

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.生成上下文菜单

@Overridepublic void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {// TODO Auto-generated method stubsuper.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.响应上下文菜单

@Overridepublic boolean onContextItemSelected(MenuItem item) {// TODO Auto-generated method stubsuper.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(){@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View childView,int flatPos, long id) {// TODO Auto-generated method stubLog.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);

0 0