Android has possibility to load menus through xml files. I found this approach very useful. I really like that I don’t need to worry about uniqueness menu item ID’s because Android generates all menu ID’s as other project IDs. In this post I want to show how you can use it in your work.
It is really easy,and you also have the same flexibility in defining menus through xml files as defining from code.
Steps which you should do for this:
- Define an XML file with menu tags
- Place the file in the /res/menu subdirectory. The name of the file is arbitrary,and you can have as many files as you want. Android automatically generates a resource ID for this menu file
- Use the resource ID for the menu file to load the XML file into the menu
- Respond to the menu items using the resource IDs generated for each menu item
Define an xml file with menu tags
Here we add one group and 2 menu items with names,IDs and orders.
Place the file in the /res/menu subdirectory
This file I called menus.xml and I saved it in /res/menu subdirectory
Use the resource ID for the menu file to load the XML file into the menu
For this thing Android has class called MenuInflater. It helps populate Menu objects from xml file.
@Overridepublic boolean onCreateOptionsMenu(Menu menu){MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.menus,menu);return super.onCreateOptionsMenu(menu)}As you see it is simple operation.
Respond to the menu items using the resource IDs generated for each menu item
This operation is also simple. You will work with their IDs as with other IDs from layouts,strings and so on.
@Overridepublic boolean onOptionsItemSelected(MenuItem item){switch (item.getItemId()){case R.id.New:doSmth();break;case R.id.Save:doSmth();break}return super.onOptionsItemSelected(item)}As you see loading menus through xml files is very simple procedure.
Also don’t forget,that you can use in the same way Context Menus.
I also want to show some additional tags which you can use in xml files.
Additional tags:
Group Category tag
Checkable Behavior tag
You can use it for group:
And also for menu item:
Submenu tag
Menu Icon tag
Menu Enabling/Disabling tag
Menu Item Shortcut tag
Menu Visibility tag
That’s all that I wanted to describe here about loading menus from xml files.
I hope that this information was useful for you.
No related posts.

Yes,declarative style is the right way to define view. By the way,as I understand,we could define in xml and inflate not only menus,but any UI layout.
Yep. I think I will show how you can do it in near future.