ExpandableListView上下文菜单的实现

本文介绍如何在Android应用中为ExpandableListView实现长按上下文菜单,并处理删除和重命名组的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先重写onCreateContextMenu方法,具体代码示例如下:
 

@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        ExpandableListView.ExpandableListContextMenuInfo info =(ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
        int type = ExpandableListView
                .getPackedPositionType(info.packedPosition);
                    if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP )
        {
               Log.i(TAG,"长按事件------在这里写任何长按之后的处理代码");
               menu.add(0,GROUP_C_MENU_DEL,0,"删除" );
               menu.add(0,GROUP_C_MENU_RENAME,0,"重命名" );
        }

       }

然后重写onContextItemSelected方法实现上下文菜单的点击事件的响应,具体代码如下: 

public boolean onContextItemSelected(MenuItem item){
        switch (item.getItemId()) { 
         case GROUP_C_MENU_DEL:
                          ExpandableListView.ExpandableListContextMenuInfo info_del=(ExpandableListView.ExpandableListContextMenuInfo)item.getMenuInfo();
             String title_del =((TextView)info_del.targetView).getText().toString();
             
             int groupPos_del =ExpandableListView.getPackedPositionGroup(info_del.packedPosition);
    MSN.msnMessenger.removeGroup(msngroup.get(groupPos_del).getGroupId()); 
             
             Log.i(TAG, groupPos_del+" ");
             contactsChild.remove(groupPos_del);
             msngroup.remove(groupPos_del);
             myExpandableListAdapter.notifyDataSetChanged();
             MSN.this.makeTip("成功删除一个组", false);
             break;
         case GROUP_C_MENU_RENAME:
             ExpandableListView.ExpandableListContextMenuInfo info_rename=(ExpandableListView.ExpandableListContextMenuInfo)item.getMenuInfo();
             String title_rename=((TextView)info_rename.targetView).getText().toString();
             
             int groupPos_rename =ExpandableListView.getPackedPositionGroup(info_rename.packedPosition);
             renameGroup(groupPos_rename);             
            break;
        }
        return false;
    }

其中获取点击的组和小孩的位置的方法如下:

int group = ExpandableListView
                .getPackedPositionGroup(info.packedPosition);
        int child = ExpandableListView
                .getPackedPositionChild(info.packedPosition);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值