You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android动态添加菜单项至菜单组失败:菜单项被添加至根节点

问题分析与解决方案

嘿,我一眼就看出问题出在哪了——你直接用根Menu对象调用add()来指定目标组ID,但那个mnuStorageLocationGroup根本不在根菜单里,它是嵌套在mnuSwitchStorageLocation的子菜单mnuStorage里面的!系统找不到这个组,就只能默认把新菜单项丢去根节点了。

修正后的代码方案

你需要先拿到那个嵌套的子菜单,再通过它来添加菜单项到目标组里,修改后的onPrepareOptionsMenu代码如下:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if ((this.storageLocations != null) && this.storageLocations.size() > 0) {
        // 先定位到根菜单里的"切换存储位置"菜单项
        MenuItem switchStorageItem = menu.findItem(R.id.mnuSwitchStorageLocation);
        // 获取它的子菜单mnuStorage
        Menu storageSubMenu = switchStorageItem.getSubMenu();
        
        if (storageSubMenu != null) {
            // 可选:如果需要清空原有测试项,避免重复添加
            // storageSubMenu.removeGroup(R.id.mnuStorageLocationGroup);
            
            for (int i = 0; i < this.storageLocations.size(); i++) {
                // 通过子菜单对象添加,确保目标组能被正确识别
                storageSubMenu.add(R.id.mnuStorageLocationGroup, Menu.NONE, Menu.NONE, storageLocations.get(i).getStorageName());
            }
        }
    }
    return super.onPrepareOptionsMenu(menu);
}

额外说明

这样修改后,新添加的菜单项会自动继承mnuStorageLocationGroup的checkableBehavior="single"属性,和你之前的测试项保持一致的选中逻辑。如果每次进入菜单都需要刷新列表,记得加上注释里的removeGroup代码,避免重复添加旧项。

内容的提问来源于stack exchange,提问作者Boardy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:43:18