Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 976
ruhalde Avatar asked Aug 12 '11 16:08

ruhalde


2 Answers

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"    android:titleCondensed="Areas"    android:title="Areas"    android:icon="@drawable/restaur"    android:enabled="true">     <menu>     <item android:id="@+id/item1" android:title="Placeholder"></item>    </menu> </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(R.menu.mapoptions, menu);              int idx=0;             SubMenu subm = menu.getItem(MYITEM_INDEX).getSubMenu(); // get my MenuItem with placeholder submenu             subm.clear(); // delete place holder              while(true)             {                 anarea = m_areas.GetArea(idx); // get a new area, return null if no more areas                 if(anarea == null)                     break;                 subm.add(0, SUBAREASID+idx, idx, anarea.GetName()); // id is idx+ my constant                 ++idx;             } } 
like image 200
2 revs, 2 users 99% Avatar answered Sep 19 '22 23:09

2 revs, 2 users 99%


I know this is an old question, but I just came across this problem myself. The most straightforward way of doing this, seems to be to simply specify the item itself as a submenu, then add to this item. E.g.:

menu.add(groupId, MENU_VIEW, Menu.NONE, getText(R.string.menu_view)); menu.add(groupId, MENU_EDIT, Menu.NONE, getText(R.string.menu_edit)); SubMenu sub=menu.addSubMenu(groupId, MENU_SORT, Menu.NONE, getText(R.string.menu_sort)); sub.add(groupId, MENU_SORT_BY_NAME, Menu.NONE, getText(R.string.menu_sort_by_name)); sub.add(groupId, MENU_SORT_BY_ADDRESS, Menu.NONE, getText(R.string.menu_sort_by_address)); : : 
like image 44
Einar H. Avatar answered Sep 22 '22 23:09

Einar H.