Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create submenus programmatically for existing Menu created from XML

Tags:

android

menu

I have created my parent menus in xml , now i don't know how to create submenus under those parents using code. That means , parents are coded in menu.xml and submenus will be loaded based on a dynamic code as and when the data is available.

When i tried to use menu.addSubMenu it is creating a new parent menu item.

like image 527
Hunt Avatar asked Jun 23 '11 11:06

Hunt


People also ask

What callback method is used to create menu items?

Inside the onCreateContextMenu() callback method, you can add menu items using one of the add() methods, or by inflating a menu resource that was defined in XML.

Which method is used to add submenu in main menu?

To add menu items and submenus to a JMenu , you use the add(JMenuItem) method.

How define menu in XML?

Define an Android Menu in XML File In android, to define menu, we need to create a new folder menu inside of our project resource directory (res/menu/) and add a new XML file to build the menu with the following elements. It's a root element to define a Menu in XML file and it will hold one or more and elements.

What is submenu menu?

Definition of submenu : a secondary menu (as in a computer application) : a list of choices that is part of another list of choices On selecting one of these sections, students should then be presented with a submenu which lists specific options related to the selected topic.—


1 Answers

I know this is a very very old thread but hopefully this will help others like me who had the same requirement.

menu/movies.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <group>
        <item
            android:id="@+id/action_filter"
            android:showAsAction="never"
            android:title="Filter">
            <menu>
                <group android:menuCategory="container">
                    <item
                        android:id="@+id/action_genre"
                        android:title="Genre">
                        <menu>
                            <group android:checkableBehavior="single" />
                        </menu>
                    </item>
                </group>
            </menu>
        </item>
    </group>
</menu>

then programmatically on your activity/fragment:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.movies, menu);
    MenuItem menuItem = menu.findItem(R.id.action_filter).getSubMenu().findItem(R.id.action_genre).getSubMenu().add(Menu.NONE, 1, Menu.NONE, "Action");
    MenuItem menuItem = menu.findItem(R.id.action_filter).getSubMenu().findItem(R.id.action_genre).getSubMenu().add(Menu.NONE, 2, Menu.NONE, "Comedy");
}

Hope this helps.

like image 56
ads Avatar answered Sep 22 '22 20:09

ads