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.
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.
To add menu items and submenus to a JMenu , you use the add(JMenuItem) method.
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.
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.—
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With