ruhalde ruhalde - 5 months ago 67
Android Question

Android adding a submenu to a menuItem, where is addSubMenu()?

I want to add a submenu inside my OptionsMenu to a menuItem, programatically according to my parameters. I've checked "MenuItem" in android sdk and there is no addSubMenu() method!, although you can find "hasSubMenu()" and "getSubMenu".

Was thinking on doing this in onCreateOptionsMenu:

public boolean onCreateOptionsMenu(Menu menu) {

MenuItem mi = menu.getItem(MYITEMID); // << this is defined in my XML optionsMenu
SubMenu subm = mi.addSubMenu(0,1,0,"Map 1"); // no addSubMenu() method!!!???

How do I create a submenu inside a menuitem in code?


Sometimes Android weirdness is really amazing (and amusing..). I solved it this way:

a) Define in XML a submenu placeholder like this:

<item android:visible="true" android:id="@+id/m_area"
    <item android:id="@+id/item1" android:title="Placeholder"></item>

b) Get sub menu item in OnCreateOptionsMenu, clear it and add my submenu items, like this:

    public boolean onCreateOptionsMenu(Menu menu) { 
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(, menu);

            int idx=0;
            subm = menu.getItem(MYITEM_INDEX).getSubMenu(); // get my MenuItem with placeholder submenu
            subm.clear(); // delete place holder

                anarea = m_areas.GetArea(idx); // get a new area, return null if no more areas
                if(anarea == null)
                subm.add(0, SUBAREASID+idx, idx, anarea.GetName()); // id is idx+ my constant