Frank
Frank

Reputation: 12300

How to add an item to a group in a submenu

At runtime I would like to add an item inside this group (in my options menu):

<item
        android:id="@+id/action_module_selector"
        android:alphabeticShortcut="m"
        android:orderInCategory="30"
        android:title="@string/module_selector_menu_title"
        app:showAsAction="never">

        <menu>
            <group
                android:id="@+id/group_modules"
                android:checkableBehavior="single">

                <!-- Modules should be added here at runtime -->

            </group>
        </menu>
    </item>

If I call subMenu.add(R.id.group_modules, moduleId, 1, title); they end up at the same level as the group, not inside the group, although I use R.id.group_modules. I would like to know how I can add them inside the group.

Upvotes: 1

Views: 405

Answers (1)

Frank
Frank

Reputation: 12300

I "solved" it by removing the group, setting the sumbMenu's items to checkable and manually making sure only one of them is selected.

subMenu.findItem(id).setCheckable(true);

and on changes:

private void updateSelectedModuleOnMenu(Menu menu, int selectedPosition) {

    MenuItem menuItem = menu.findItem(R.id.action_module_selector);
    SubMenu subMenu = menuItem.getSubMenu();

    for (int i = 0; i < subMenu.size(); i++) {
        MenuItem item = subMenu.getItem(i);
        item.setChecked(i == selectedPosition);
    }
}

A solution using a group I could not find.

Upvotes: 1

Related Questions